Monday 17 March 2014

how to create delegate in c# with example.

Delegate:- 

delegate means transfer power to someone.delegate looking same function to pointer in C or C++.using delegate method    allows the programmer to encapsulate a reference to method inside a delegate object.

Two types delegate 1) single cast : One object referring one function show example 1.
                              2)  multi cast : One object referring many function. show example 2.


signature should be same which function pass to delegate.
In delegate show main three point
  1) Declaring a delegate.

Declare a new delegate type.each delegate describes the number and types of argument and type of return value of methods that ti can encapsulate. 
The following statement  :- delegate void mydel(int a, int b);

                                               
     2) Instantiating a delegate. 
Once create delegate after create instantiating object must create associated with a particular method. argument pass with new expression is special .it is written like a method call, but without the argument to the method.
The following statement :-  mydel d1 = new mydel(p.add); (This is for single cast).
                                          d1+= new mydel(p.multiply); (This is for multi cast).


                                                   
 3)Calling a delegate.
Once delegate object create . delegate object typically pass to other code .that will call delegate.
The following statement :- d1(4, 5);

Use delegate show the example 1.

Output:


example 2:

Output:

0 comments:

Post a Comment