Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic overloaded method resolution problems

Tags:

c#

I have two methods with these signatures:

void Method<T>(T data)
{
}

void Method<T>(IEnumerable<T> data)
{
}

Its an overload of the same method to take either a single object or a list of them. If I try to pass a List<'T> to it, it resolves to the first method, when obviosly i want the second. I have to use list.AsEnumerable() to get it to resolve to the second. Is there any way to make it resolve to the second regardless of whether the list is type T[], IList<'T>, List<'T>, Collection<'T>, IEnumerable<'T>, etc.

like image 640
user380689 Avatar asked Jul 22 '10 07:07

user380689


1 Answers

The best solution: do not go there in the first place. This is a bad design. You'll note that none of the framework classes do this. A list has two methods: Add, and AddRange. The first adds a single item, the second adds a sequence of items.

It's a bad design because you are writing a device for automatically producing bugs. Consider again the example of a mutable list:

List<object> myqueries = new List<object>();
myqueries.Add(from c in customers select c.Name);
myqueries.Add(from o in orders where o.Amount > 10000.00m select o);

You'd expect that to add two queries to the list of queries; if Add were overloaded to take a sequence then this would add the query results to the list, not the queries. You need to be able to distinguish between a query and its results; they are logically completely different.

The best thing to do is to make the methods have two different names.

If you're hell bent on this bad design, then if it hurts when you do that, don't do that. Overload resolution is designed to find the best possible match. Don't try to hammer on overload resolution so that it does something worse. Again, that is confusing and bug prone. Solve the problem using some other mechanism. For example:

static void Frob(IEnumerable ts) // not generic!
{
    foreach(object t in ts) Frob<object>(t);
}
static void Frob<T>(T t)
{
    if (t is IEnumerable)
        Frob((IEnumerable) t);
    else
        // otherwise, frob a single T.
}

Now no matter what the user gives you - an array of T, an array of lists of T, whatever, you end up only frobbing single Ts.

But again, this is almost certainly a bad idea. Don't do it. Two methods that have different semantics should have different names.

like image 119
Eric Lippert Avatar answered Oct 12 '22 22:10

Eric Lippert