2

Im not sure, but is it called inlining when you do it all in one line?

I my code i have this BackgroundWorker. The DoWorker enforce a sleep of on sec and the RunWorkerCompleted just does noe bit of code. Would it be possible to instead of defining a function do it all in one line like

.DoWork += ((sender, arg) => { ... }); 

and

.RunWorkerCompleted += ((sender, arg...

What is the right syntax for this, and what is this called? Its nice to keep things simple when you have a simple task at hand :-)

Digital Alchemist
  • 2,324
  • 1
  • 15
  • 17
Jason94
  • 13,320
  • 37
  • 106
  • 184

1 Answers1

1

You are confusing inlining with lambda expressions. Inlining is replacing the calling of a method by its body, for example:

int TimesTwo(int x) 
{
   return x * 2;
}

//before inlining:
int a = TimesTwo(6) + TimesTwo(7);
//after inlining:
int a = 6 * 2 + 7 * 2;

This is a compiler optimization technique to avoid method call overhead.

For your BackgroundWorker example the correct syntax would be:

 BackgroundWorker worker = new BackgroundWorker();
 worker.DoWork += (sender, e) => RunMyMethod();
 //or
 worker.DoWork += (sender, e) => { RunMyMethod(); }

For more information see MSDN.

Bas
  • 26,772
  • 8
  • 53
  • 86