Tuesday, August 6, 2013

Delegate in C#

Delegate
A delegate is a type that defines method signature. An instance of delegate can be associate with any compatible signatures.  Later on we can invoke any method through delegate instance.
Delegates can be used to pass method as argument to another method. This ability makes delegates ideal for defining callback methods.
Properties of delegates
  • Delegates are method pointers. Unlike C++ it is type safe. Delegates allow passing method as parameter.
  • Delegates can be used to define call back method.
  • Delegates can be combined together.
  • We can pass code block as parameter in delegates. It is called anonymous method.
  • Delegates support Covariance and Contravariance.
  • Delegates can be overloaded.

 Now let’s explore delegate more with an example.
 
  • abc is a class having one method function1. Function 1 takes one string type argument. And it has a  return type of void. 
  • A delegate mydelegate is declared with one string type parameter and void return type.
  • Creating the instance of mydelegate and associate function1 with the instance.
  • Now at last need to invoke the method by delegate.  It is very easy to invoke. Just pass the parameter with delegate object. 
Different implementation of delegate