views:

146

answers:

6

I am using generics to translate Java code to C# and having trouble with containers of the sort:

public static class MyExtensions
{
    public static void add(this List<object> list, object obj)
    {
        list.Add(obj);
    }
    public static void add(this List<string> list, string s)
    {
        list.Add(s);
    }
}

It seems that the generics are lost in comparing arguments and the two methods collide. I'd like any advice on whether generics can be used in this way. Is it possible to support all list operations with a single:

    public static void add(this List<object> list, object obj)
    {
        list.Add(obj);
    }

for example?

SUMMARY All responses have the same solution. List can be abstracted to ICollection. Overall it's probably not a good idea for production code.

+10  A: 

How about:

public static void add<T>(this IList<T> list, T value)
{
    list.Add(value);
}

(actually, it could be ICollection<T>, since this (not IList<T>) defines Add(T))

Marc Gravell
+5  A: 

Have you tried:

public static void add<T>(this List<T> list, T obj)
{
    list.Add(obj);
}

I'm not sure if you'd want to constrain it to a class or not, but that should do what you're describing.

Joseph
+5  A: 

Do you mean this:

public static void add<T>(this List<T> list, T obj)
{
    list.Add(obj);
}
M4N
+5  A: 

I think Marc Gravell answered this best, but I will add:

Don't do this at all. There is no advantage to:

myList.add(obj);

vs

myList.Add(obj);

The only "advantage" here is that your resulting C# will look wrong to most developers. If you're going to port from Java to C#, it's worth taking the extra time to make your methods look and work like native .NET methods.

Reed Copsey
@Reed I agree. This is an interim solution to see how easily the code ports. It will avoid errors made by overzealous automatic editing. When the system compiles I will decide how we move towards a better solution.
peter.murray.rust
A: 

The most versatile way:

public static void add<T>(this ICollection<T> list, T obj) // use ICollection<T>
{
    list.Add(value);
}
DreamWalker
A: 

@Dreamwalker, did you mean? list.Add(obj);

tom d