user1483278
user1483278

Reputation: 949

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

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

Upvotes: 4

Views: 138

Answers (2)

Lee
Lee

Reputation: 144206

There's no type inference in your second example - you are explicitly giving the delegate type to use. In this case you need to provide the type parameter since there is no non-generic GenDel type.

Upvotes: 4

SLaks
SLaks

Reputation: 888223

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

Upvotes: 8

Related Questions