Saturday, March 1, 2014

Delegates

Delegates

This is the new concept introduced in C#.
Def: A delegate is the reference to the method. Using the delegate, you can call the method. This is used in "GUI Events" and "Multi-Threading" concept in future.
Implementation Syntax:
  • Define the Method:
               accessmodifier returntype methodname(arguments)
                  {
                     //some code
                  }

  • Declare the delegate (as a data member):
             delegate returntype delegatename(arguments);
  • Create instance of the delegate:
             delegatename delegateinstancename = new delegatename(methodname);
  • Access the properties of the delegate:
                 delegateinstancename.Target
          //gets the class name that contains the target method
               delegateinstancename.Method
         //gets the signature of the target method

  • Invoke / call the target method:
                       delegateinstancename.Invoke();
                       (or)
            delegateinstancename.Invoke(arguments);



Delegates

Download above code for Demo on Delegates : Download Links

 Multi Cast Delegates

  • It contains the address of multiple methods.
  • You can add the reference of the methods, one by one using ―+=‖ operator.
  • When you call the methods using ―Invoke()‖ method, all the methods will be called at-atime.
Rule: All of the methods should have same return type and same arguments set.
Limitation: If there is any return value, you can get only the last returned value.
Multi Cast Delegates

Download above Code for Demo on Multi Cast Delegates : Downloads Links