Alex Rivera | Logout

Generic methods in .NET cannot have their return types inferred. Why?

Asked 2010-07-08T12:42:16.897
61

Given:

static TDest Gimme<TSource,TDest>(TSource source) 
{ 
    return default(TDest); 
}

Why can't I do:

string dest = Gimme(5);

without getting the compiler error:

error CS0411: The type arguments for method 'Whatever.Gimme<TSource,TDest>(TSource)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

The 5 can be inferred as int, but there's a restriction where the compiler won't/can't resolve the return type as a string. I've read in several places that this is by design but no real explanation. I read somewhere that this might change in C# 4, but it hasn't.

Anyone know why return types cannot be inferred from generic methods? Is this one of those questions where the answer's so obvious it's staring you in the face? I hope not!

Edit
Report

1 Answer

0

If a function is supposed to return one of a small number of types, you could have it return a class with defined widening conversions to those types. I don't think it's possible to do that in a generic way, since the widening ctype operator doesn't accept a generic type parameter.

answered 2010-07-08T17:12:11.243

Your Answer