views:

175

answers:

2

I am looking at the BackgroundWorker.ReportProgress method. It can take 1 param (int) or two params (int, object).

If I want to assign the ReportProgress like this:

var ReportProgressMethod = backgroundWorker.ReportProgress;

I get an error saying that there is an ambiguous reference because (of course) the method can take to sets of parameters.

How can I change the above statement to say I want to use the int, object version of the method.

(The idea behind this is that I want to pass ReportProgressMethod as a parameter to a method.)

+13  A: 
Action<int, object> reportProgressMethod = backgroundWorker.ReportProgress;
280Z28
thanks for marking the code. I wasn't sure about the compiler being able to use type info from the lhs to determine the method overload
Rune FS
How bizzare, that totally works...
Igor Zevaka
+2  A: 

There's multiple ways you can help the compiler but basically you just need to make the delegate type explicit in one way or another. My preferred would be this:

var ReportProgressMethod = new Action<int,object>(backgroundWorker.ReportProgress);

that's what the compiler will do anyways (instantiate a new delegate, whether or not your writing new) but igor is correct in his comments that a cast would work as well.

Rune FS
I don't think the current compiler infers delegate types.
Jimmy
Argh and SO is removing the angles when it's not code
Rune FS
@jimmy it does when it's typed on the right hand side but not if the rhs is a lambda expression
Rune FS
You got the brackets the wrong way around. This works: `var blah = (Action<int, object>)worker.ReportProgress`;
Igor Zevaka
@Igor no I didn't get the brackets the wrong way. It's an instantiation and it works just fine /as does your suggestion with a cast but that cast is redundant since your example will actually compile to an instantiation and a cast)
Rune FS
Indeed you are right, I missed the `new`. Whats the bet all three ways (included the accepted answer compile to the same IL?
Igor Zevaka
@Igor from this post http://stackoverflow.com/questions/2216763/c-compiler-doesnt-optimize-unnecessary-casts I'd say the pets are that 280Z28s and mine compile to the same IL (since they are semantically equal) but I',m betting that the cast will be left there
Rune FS