Craig Walker
Craig Walker

Reputation: 51707

Ambiguous Call with a Lambda in C# .NET

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?

Upvotes: 6

Views: 1285

Answers (3)

Craig Walker
Craig Walker

Reputation: 51707

The way I know is to use an old-style delegate:

MyClass.DoThis( delegate(Foo foo) {
  foo.DoSomething();
});

This is a lot more verbose than a lambda. I'm also concerned that it may not be work if yoiu want an expression trees, though I'm not sure about this.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062512

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

Upvotes: 23

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421968

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()));

Upvotes: 2

Related Questions