Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Can someone tell me why and where I should use delegates? [duplicate]

Tags:

c#

delegates

I think I understand the concept of a delegate in C# as a pointer to a method, but I cant find any good examples of where it would be a good idea to use them. What are some examples that are either significantly more elegant/better with delegates or cant be solved using other methods?

like image 991
Alex Avatar asked Jan 29 '09 12:01

Alex


1 Answers

The .NET 1.0 delegates:

this.myButton.Click += new EventHandler(this.MyMethod);

The .NET 2.0 delegates:

this.myOtherButton.Click += delegate {
    var res = PerformSomeAction();
    if(res > 5)
        PerformSomeOtherAction();
};

They seem pretty useful. How about:

new Thread(new ThreadStart(delegate {
    // do some worker-thread processing
})).Start();
like image 73
yfeldblum Avatar answered Sep 30 '22 15:09

yfeldblum