Delegate(s): A delegate is a reference type variable that holds the reference to a method.
1. Declare Delegate:Following is a syntax for declaring a delegate
delegate <return type> delegatename(parameter....)
e.g.
delegate int Add(int x, int y);
If you feel problem to remember syntax of declaring delegate, just remember how we declare n abstract method and prefix delegate keyword instead of abstract keyword.
2. Create object of delegate
Add _a;
3. Pass method which need to be called by delegate
There are three methods by which we can invoke or call delegate
- Named methods
- Anonymous methods
- Lambda Expression
1. Named Method-This is the traditional method which is available from detent 1.0.mechanism .In this we create a method and pass it to object of delegate we had created in Step 2
- 3.1.1 Create a method Add
static int AddNum(int x, int y)
{
return x + y;
}
- 3.1.2 Use Delegate object and invoke add
function
_a = AddNum;
2. C#2.0 introduces a new mechanism for calling delegate known as Anonymous methods
In Anonymous method instead of creating a method and passing it to delegate object as we do in case of Named method. We passed a code of block to delegate. This will reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.
Add _a
= delegate(int x, int y)
{
return x
+ y;
};
3. A lambda expression is an anonymous function that you can use to create delegates
_a =( int x,int y) => x + y;
4.0 Now you can invoke the delegate, irrespective by which mechanism we had pass delegate code to it.
int returnValue=_a(10, 12);
Join the conversation! Your thoughts help the community grow.