7

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.

Community
  • 1
  • 1
Pieter van Ginkel
  • 29,160
  • 8
  • 71
  • 111
  • Thank you very much. Searched but I couldn't find it. – Pieter van Ginkel Sep 08 '11 at 18:52
  • @Pieter: The post mentioned by Darin has the answer, and has some good links to more info. – James Michael Hare Sep 08 '11 at 18:53
  • Read 10 posts or something, but the above one wasn't among them. – Pieter van Ginkel Sep 08 '11 at 18:56
  • @Pieter: first hit here: http://www.google.com/#sclient=psy&hl=en&source=hp&q=c%23+infer+delegate+generic&pbx=1&oq=c%23+infer+delegate+generic&aq=f&aqi=&aql=&gs_sm=e&gs_upl=3066l4016l1l4115l8l7l0l0l0l0l214l696l0.3.1l4l0&bav=on.2,or.r_gc.r_pw.&fp=b7e6040383bebbf&biw=1440&bih=795 – Darin Dimitrov Sep 08 '11 at 18:59
  • Yep, you're right. I however searched through the suggestions that were presented when asking the question. May'be I'll put a bit more effort in searching the next time :). – Pieter van Ginkel Sep 08 '11 at 19:00
  • more relevant link http://stackoverflow.com/questions/6229131/why-cant-c-sharp-infer-type-from-this-seemingly-simple-obvious-case – nawfal Oct 10 '12 at 10:16

3 Answers3

2

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
dlev
  • 48,024
  • 5
  • 125
  • 132
0

Just put this is a compiler I see what you mean.

I think it's because Action is used as a method group, but it's not of type Action<int>.

If you cast it to this type it works:

Method((Action<int>)Action);
TheCodeKing
  • 19,064
  • 3
  • 47
  • 70
0

This works:

    static void Main(string[] args)
    {
        Method<int>(Action);
    }

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

    static void Method<T>(Action<T> action)
    {
        // ...
    }
Samich
  • 29,157
  • 6
  • 68
  • 77