using generics in c# extension functions

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.

13.10.2009 19:07:10
What do you mean by "the two methods collide"? The class shown compiles with no errors.
Jon Skeet 13.10.2009 19:16:21
When I call methods of the form myList.add(foo) it reports than it cannot find the correct method - it has the wrong arguments
peter.murray.rust 13.10.2009 19:31:01
Make sure the namespace of this class has been included in the file, via "using MyExtensionsNamespace;"
Reed Copsey 13.10.2009 19:39:52
6 ОТВЕТОВ
РЕШЕНИЕ

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))

10
13.10.2009 19:11:31

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.

5
13.10.2009 19:12:07

Do you mean this:

public static void add<T>(this List<T> list, T obj)
{
    list.Add(obj);
}
5
13.10.2009 19:12:14

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.

5
23.05.2017 12:04:21
@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 13.10.2009 19:57:30

The most versatile way:

public static void add<T>(this ICollection<T> list, T obj) // use ICollection<T>
{
    list.Add(value);
}
0
13.10.2009 19:35:02

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

0
13.10.2009 20:53:08