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.
source to share
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.
source to share