5

I just stumbled upon an error I cannot explain.

The following code causes a compiler error in Visual Studio 2015:

class Program {
  private static void DoSomethingWithParameter(string s) { }

  private static void RegisterMethod<T>(Action<T> method) { }

  static void Main(string[] args) {
    RegisterMethod(DoSomethingWithParameter);
  }
}

Error:

Error CS0411 The type arguments for method 'Program.RegisterMethod<T>(Action<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

If I change the method call to

RegisterMethod<string>(DoSomethingWithParameter);

it works.

I think the compiler should be able to infer the correct type from the first method call, but that's not the case. Can anybody explain this to me, please?

fss
  • 113
  • 1
  • 5
  • If you don't specify type explicitly then `RegisterMethod(s => DoSomethingWithParameter(s))` will fail to compile. `s` is `T` not string. and method groups are just syntactic sugar of some lambda expressions. – M.kazem Akhgary Jan 03 '17 at 15:29
  • 1
    Thanks @patrick-hofman. The linked topic resolved the question. – fss Jan 03 '17 at 15:32

0 Answers0