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.)

Vaccano
  • 78,325
  • 149
  • 468
  • 850

2 Answers2

13
Action<int, object> reportProgressMethod = backgroundWorker.ReportProgress;
Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
  • 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 Feb 08 '10 at 07:13
2

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
  • 21,497
  • 7
  • 62
  • 96
  • I don't think the current compiler infers delegate types. – Jimmy Feb 08 '10 at 07:09
  • @jimmy it does when it's typed on the right hand side but not if the rhs is a lambda expression – Rune FS Feb 08 '10 at 07:11
  • You got the brackets the wrong way around. This works: `var blah = (Action)worker.ReportProgress`; – Igor Zevaka Feb 08 '10 at 07:27
  • @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 Feb 08 '10 at 08:43
  • 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 Feb 08 '10 at 20:24
  • @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 Feb 08 '10 at 20:42