tags:

views:

97

answers:

3

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?

+2  A: 

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()));
Mehrdad Afshari
+13  A: 
MyClass.DoThis((Foo foo) => foo.DoSomething());
Marc Gravell
A: 

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.

Craig Walker