Ok I must have got the title terribly wrong. More code, less words:
public class Manager<T> where T : Control, new()
{
void Manage()
{
Do(t => IsVisible(t));
}
bool IsVisible(T t)
{
return t.Visible;
}
S Do<S>(Func<T, S> operation)
{
return operation(new T());
}
}
The compiler is happy about Do. It can infer the T type easily. Now lets say I have this:
public static class Util
{
static void Manage()
{
Do(t => IsVisible(t)); //wiggly line here
}
static bool IsVisible<T>(T t) where T : Control
{
return t.Visible;
}
static S Do<S, T>(Func<T, S> operation) where T : Control, new()
{
return operation(new T());
}
}
The compiler wants types to be explicitly typed now. Here is what I think:
In the first class T was easily inferable from IsVisible method which had T overload and T is known all over the Manager class, no big deal. But in the second case T is specified as a generic constraint on the method and may be that’s harder to infer. Ok.
But this doesn’t work either:
public static class Util
{
static void Manage()
{
Do(t => IsVisible(t)); //still wiggly line
}
static bool IsVisible(Control t)
{
return t.Visible;
}
static S Do<S, T>(Func<T, S> operation) where T : Control, new()
{
return operation(new T());
}
}
-
Why doesn’t compiler infer
Tin the last case? -
More importantly, how different is the last case from the first? In the first case compiler have to infer it from
IsVisiblemethod and then go all the way back to check whatTis in the class containingIsVisible, where as in the last case its readily available inIsVisiblemethod. So I assume third case is easier than the first.
(First case)
It’s not inferring
Tat all.Tis a type parameter for the class:(Second case)
I assume you mean in the Manage code:
And that’s right. What do you think the type of
Tshould be here? How would you expect the complier to infer it?(Third case, where the method is
IsVisible(Control t))It can’t do so from just the parameters. It sounds like you’re expecting it to work out every type for which the body of the lambda expression could work… and type inference simply doesn’t work that way. You can easily give the compiler enough information though:
In the first case,
Tisn’t a type parameter for theDomethod. The compiler only needs to inferS, which it can do from the return type of the lambda expression. It doesn’t need to perform any inference forT, because that’s already “known”. (It’s still generic, but it’s not something which needs to be inferred for that method call.) The type ofTwill need to be supplied when constructing an instance ofManagerin the first place, so it’s effectively moving that decision.For all the gory details of type inference, see section 7.5.2 of the C# 4 spec (or the equivalent section in the C# 3 or C# 5 specs). I’d advise a strong cup of coffee first though 🙂