Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous Call with a Lambda in C# .NET

Tags:

c#

.net

lambda

I have a class with an overloaded method:

MyClass.DoThis(Action<Foo> action);
MyClass.DoThis(Action<Bar> action);

I want to pass a lambda expression to the Action version:

MyClass.DoThis( foo => foo.DoSomething() );

Unfortunately, Visual Studio rightly cannot tell the difference between the Action<Foo> and Action<Bar> versions, due to the type inference surrounding the "foo" variable -- and so it raises a compiler error:

The call is ambiguous between the following methods or properties: 'MyClass.DoThis(System.Action<Foo>)' and 'MyClass.DoThis(System.Action<Bar>)'

What's the best way to get around this?

like image 659
Craig Walker Avatar asked Feb 12 '10 17:02

Craig Walker


2 Answers

MyClass.DoThis((Foo foo) => foo.DoSomething());
like image 123
Marc Gravell Avatar answered Sep 25 '22 08:09

Marc Gravell


There's no way the compiler could figure that out by itself. The call is indeed ambiguous and you'll have to somehow clarify the overload you want for the compiler. The parameter name "foo" is insignificant here in the overload resolution.

MyClass.DoThis(new Action<Foo>(foo => foo.DoSomething()));
like image 22
mmx Avatar answered Sep 21 '22 08:09

mmx