Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't these type arguments be inferred? [duplicate]

Possible Duplicate:
C# 3.0 generic type inference - passing a delegate as a function parameter

Why can't the type arguments of the following code sample in the call in Main be inferred?

using System;

class Program
{
    static void Main(string[] args)
    {
        Method(Action);
    }

    static void Action(int arg)
    {
        // ...
    }

    static void Method<T>(Action<T> action)
    {
        // ...
    }
}

This gives the following error message:

error CS0411: The type arguments for method Program.Method<T>(System.Action<T>) cannot be inferred from the usage. Try specifying the type arguments explicitly.

like image 668
Pieter van Ginkel Avatar asked Sep 08 '11 18:09

Pieter van Ginkel


1 Answers

The problem is that Action (aside from already being a type; please rename it) is actually a method group that is convertible to the delegate type Action<int>. The type-inference engine can't infer the type because method group expressions are typeless. If you actually cast the method group to Action<int>, then type-inference succeeds:

Method((Action<int>)Action); // Legal
like image 75
dlev Avatar answered Nov 12 '22 08:11

dlev