What is delegate?
Delegates are objects you can use to call the methods of other objects.
A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the name of the delegate.
Once a delegate is assigned a method, it behaves exactly like that method.
The delegate method can be invoked like any other method, with parameters and a return value.
Any method from any accessible class or struct that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate.
The method can be either static or an instance method. This makes it possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the signature of the delegate, you can assign your own delegated method.
Delegates have the following properties:
Delegates are like C++ function pointers but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Methods do not have to match the delegate signature exactly.
Delegates are like C++ function pointers but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Methods do not have to match the delegate signature exactly.
how to use Delegates ?
or
1. Defining the delegate
public delegate int Calculate (int value1, int value2);
2. Creating methods which will be assigned to delegate object
//a method, that will be assigned to delegate objects //having the EXACT signature of the delegatepublic int add(int value1, int value2) { return value1 + value2; }//a method, that will be assigned to delegate objects //having the EXACT signature of the delegatepublic int sub( int value1, int value2) { return value1 - value2; }
3. Creating the delegate object and assigning methods to those delegate objects
//creating the class which contains the methods //that will be assigned to delegate objectsMyClass mc = new MyClass(); //creating delegate objects and assigning appropriate methods //having the EXACT signature of the delegateCalculate add = new Calculate(mc.add); Calculate sub = new Calculate(mc.sub);
4. Calling the methods via delegate objects
//using the delegate objects to call the assigned methods Console.WriteLine("Adding two values: " + add(10, 6)); Console.WriteLine("Subtracting two values: " + sub(10,4));
No comments:
Post a Comment