Wednesday, May 20, 2015

6. Delegates

A delegate is a reference to a function (single cast delegate) or to multiple functions (multi cast delegate)

Here's the implementation of a multi cast delegate:

//1. Declaration
public delegate void MyDelagate(int a, int b); 
public class Example
{
 // methods to be assigned and called by delegate
 public void Sum(int a, int b)
 {
 Console.WriteLine("Sum of integers is = " + (a + b));
 }
 
 public void Difference(int a, int b)
 {
 Console.WriteLine("Difference of integer is = " + (a - b));
 }
}
class Program
{
 static void Main()
 {
 Example obj = new Example();
 // 2. Instantiation
 MyDelagate multicastdel = new MyDelagate(obj.Sum); 
 multicastdel += new MyDelagate(obj.Difference);
 
 // 3. Invocation
 multicastdel (50, 20);
 }
}
 
/* Out put
 
 Sum of integers is = 70 
 Difference of integer is = 30
 
*/

No comments:

Post a Comment