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?
MyClass.DoThis((Foo foo) => foo.DoSomething());
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With