Delegate - How to call a method of a class ?

Akiii
Posted by Akiii under C# category on | Points: 40 | Views : 1222
Hi,
Today i will show you how to call a method of a class with the help of a Delegate .
First, we declare a class name "Test" :-

public Class Test
{
public int myMethod(int i, int j)
{
return i + j;
}
}


Now, we will declare a Delegate signature:-
public delegate int myDelegate(int x, int y);



Now, how we will call the class method with the help of a Delegate, pretty tough huh...! not at all, follow the example :-

public static void main(string[] args)
{
Test objTest = new Test();
myDelegate objDelegate = new myDelegate(objTest.myMethod );
Console.Writeline("Summation is : " + objDelegate(3, 5) );
}



output:-
8


Its an excellent feature given to us, so use it !

I hope the explanation is clear enough...

Thanks and Regards
Akiii

Comments or Responses

Login to post response