Using generics in C # extension functions
I am using generics to translate Java code to C # and sorting container issues:
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 looks like generics get lost when comparing arguments and both methods collide. I would like any advice on whether generics can be used this way. Is it possible to support all list operations with one:
public static void add(this List<object> list, object obj)
{
list.Add(obj);
}
eg?
SUMMARY All answers have the same solution. The list can be referred to as ICollection. Overall, this is probably not a good idea for production code.
What about:
public static void add<T>(this IList<T> list, T value)
{
list.Add(value);
}
(actually it can be ICollection<T>
, since it (does not IList<T>
) define Add(T)
)
You tried:
public static void add<T>(this List<T> list, T obj)
{
list.Add(obj);
}
I'm not sure if you want to restrict it to a class or not, but it should do what you describe.
You mean this:
public static void add<T>(this List<T> list, T obj)
{
list.Add(obj);
}
I think Mark Gravell answered this in the best possible way , but I'll add:
Don't do it at all. No benefits:
myList.add(obj);
against
myList.add(obj);
The only "advantage" here is that your final C # will not look right to most developers. If you're going to port from Java to C #, it's worth spending the extra time to make your methods look and work like native .NET methods.
The most versatile way:
public static void add<T>(this ICollection<T> list, T obj) // use ICollection<T>
{
list.Add(value);
}
@Dreamwalker, you mean? list.Add(obj);