4

I imported a project into Visual Studio that I wanna check out the source code from and experiment compiling it, but I get the error mentioned in about 20 different places in the same CS files.

Here's one example section of code that throws the error: (The error is the entire overload passed to this.Invoke).

  if (this.InvokeRequired)
  {
    this.Invoke((Delegate) (() => this.CheckVersionInfo()));
  }
stingray-11
  • 448
  • 2
  • 7
  • 25
  • lots of info on this here http://stackoverflow.com/questions/2367718/automating-the-invokerequired-code-pattern – Anton Aug 15 '13 at 06:10

2 Answers2

4

You can only convert from lambda expressions to specific delegate types. In this particular case it's really easy though - you can just use Action instead (or MethodInvoker, or any delegate type with no parameters and a void return type):

if (this.InvokeRequired)
{
  this.Invoke((Action) (() => this.CheckVersionInfo()));
}

Or just use a method group conversion to simplify things:

if (this.InvokeRequired)
{
  this.Invoke((Action)CheckVersionInfo);
}

Alternatively, add an extension method to Control or ISynchronizeInvoke either just to add an Invoke(Action) method, or a "check and invoke" method. (Both can be useful, in different contexts.)

To be honest though, I would be very nervous of the rest of the code you're importing if it's basically broken like this. If the code doesn't even compile to start with, how much confidence do you have that it will work once you've fixed the most obvious errors?

Note that this isn't just a matter of different versions of C# or anything like that - the code you've posted would never have worked, in any version of C#.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • _the code you've posted would never have worked, in any version of C#_ , I was just about to ask you about that :) – Alex Filipovici Aug 15 '13 at 06:13
  • Thanks for the answer, but when I try it it gives me this error: 'EUsing the generic type 'System.Action' requires 1 type arguments' – stingray-11 Aug 15 '13 at 06:20
  • Actually it seems that works if I change the .NET version to 3.5. This project was using 2.0. – stingray-11 Aug 15 '13 at 06:21
  • 1
    @user1653653: Oh, are you using .NET 2.0? (The non-generic `Action` class was introduced in .NET 3.5.) In that case either declare an `Action` delegate yourself or use `MethodInvoker`.) In future, if you're using a version of .NET which is that far behind the current version, please indicate that in the question :) – Jon Skeet Aug 15 '13 at 06:21
0

Try this:

this.Invoke(new MethodInvoker(() => this.CheckVersionInfo()));
Alex Filipovici
  • 31,789
  • 6
  • 54
  • 78