I\'m gonna create a BackgroundWorker with an anonymous method.
I\'ve written the following code :
BackgroundWorker bgw = new B
Lambda expressions are really handy to make the code shorter and more readable. However entry level programmers might find it a bit difficult to deal with. There are three separate concepts one should go through: anonymous methods, delegates and lambda expressions. A detailed walk-through of each of them is beyond the scope of this answer. I hope that the code example given below will serve the purpose of giving a quick view of the different approaches available.
class TestBed
{
BackgroundWorker bgw = new BackgroundWorker();
void sample()
{
//approach #1
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
//DoWorkEventHandler is nothing but a readily available delegate written by smart Microsoft guys
//approach #2, to make it a little shorter
bgw.DoWork += (s,e) =>
{
//...
};
//this is called lambda expression (see the => symbol)
//approach #3, if lambda scares you
bgw.DoWork += delegate
{
//... (but you can't have parameters in this approach
};
//approach #4, have a helper method to prepare the background worker
prepareBgw((s,e)=>
{
//...
}
);
//approach #5, helper along with a simple delegate, but no params possible
prepareBgw(delegate
{
//...
}
);
//approach #6, helper along with passing the methodname as a delegate
prepareBgw(bgw_DoWork);
//approach #7, helper method applied on approach #1
prepareBgw(new DoWorkEventHandler(bgw_DoWork));
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
//...
}
void prepareBgw(DoWorkEventHandler doWork)
{
bgw.DoWork+= doWork;
}
}
Note that we used "delegate" and not "Delegate" in this example (there is a difference between the two)