Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't generic method able to infer a parameter type?

Tags:

c#

generics

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 above example the generic method receives lambda expression as a parameter ( genMet(() => "Works"); ), and from this lambda expression method is able to infer parameter types.

Why isn't method also able to infer parameter type in the next example, where instead of lambda expression we pass a delegate instance as a parameter:

        genMet(new GenDel(() => "Doesn't work")); // Error: Using the generic type 'GenDel<T>' 
                                                  // requires 1 type arguments
like image 270
user1483278 Avatar asked Dec 16 '22 16:12

user1483278


1 Answers

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

like image 99
SLaks Avatar answered Dec 31 '22 02:12

SLaks