Why can't the generic method infer the type of the parameter?

public delegate T GenDel<T>(); class Program { public static void genMet<T>(GenDel<T> d) { } static void Main(string[] args) { genMet(new GenDel<string>(() => "Works")); genMet(() => "Works"); } } 

In the above example, the general method accepts the lambda expression as the parameter ( genMet(() => "Works"); ), and from this method the lambda expression can derive the types of parameters.

Why the method cannot deduce the type of the parameter in the following example, where instead of the lambda expression we pass the delegate instance as the parameter:

  genMet(new GenDel(() => "Doesn't work")); // Error: Using the generic type 'GenDel<T>' // requires 1 type arguments 
+4
source share
2 answers

Type inference applies only to generic methods, not to generic types or their constructors.

+8
source

In your second example, there is no type inference - you are explicitly using the delegate type. In this case, you need to specify the type parameter, since there is no GenDel generic type.

+4
source

All Articles