Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 800
peter.murray.rust Avatar asked Feb 07 '26 04:02

peter.murray.rust


2 Answers

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

like image 184
Marc Gravell Avatar answered Feb 08 '26 18:02

Marc Gravell


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.

like image 32
Joseph Avatar answered Feb 08 '26 17:02

Joseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!