I have the following setup:
public abstract class super { }
public class sub : super { }
public static void Foo<T>(T element, Action<T> action)
where T : new()
{ }
And I want to do this:
Action<super> superAction = (s) => { };
Foo(new sub(), superAction);
However, this fails because the second line is trying to call Foo<super>
instead Foo<sub>
. This will work:
Foo<sub>(new sub(), superAction);
- Is it necessary in any case to display the type parameter in this case?
- Why doesn't this infer the correct type in the first place?
EDIT:
The problem boils down to what is possible:
Action<sub> subAction = superAction;
But the compiler does not use this fact for output logic.
So, the answer to question 1:
Foo(new sub(), superAction as Action<sub>);
Question 2, why the compiler does not do this on its own, is still unresolved.
EDIT2:
2:
. , " " ( ). .
(, where
, T : new()
), .