Deligate RRS feed

  • Question

  • Hi, why Deligates  use in C#,what is the benefit of Deligates 
    Friday, January 22, 2016 4:03 PM


  • Have a read of this.

    As the article in that link says, delegates are kind of like 'pointers to functions'. They have lots of uses.

    For example, they allow you to hook up events on a control: A button control needs to do something when clicked, but the designer of the button control obviously can't know what that is. The answer is that the button control provides an "event", which is a delegate type. The calling code - the code that uses the button - can then provide the specific function and then hook that code to the button clicked event, which really means setting the button clicked event to the delegate of your function (now the button clicked event 'points' to your function and can invoke it when clicked).

    Another use is callback methods. You might need a method that reports back on its progress while its working. To do this you can pass a delegate into that method. The calling code calls the method and passes in a delegate (a 'pointer') to a function that updates a progress bar or whatever.

    The biggest difference between a delegate and c++ 'function pointer' is that delegates are type-safe. A delegate must be defined to only refer to a function of a specific prototype. For example you may define a delegate to only refer to functions that accepts a single string argument and return a boolean. When used, only functions that follow that exact pattern may be used wherever a delegate of that type is required.

    See the examples on that article mentioned above or just search "delegates c# examples".

    Friday, January 22, 2016 4:16 PM