1.

What is a delegate?

Answer»

A delegate is a reference type entity that is used to store the reference of a method. So whenever you need to call a method, you can easily use the delegate by initializing a pointer to that method, thereby helping to implement Encapsulation.

// C# program to show the use of Delegates
using System;
namespace DelegateExample {

// Declare class "DelegateExampleClass"
class DelegateExampleClass {

// Declaring the delegates -
// "addTwoNumbers", and "substractTwoNumbers"

// The return type and parameter type of the
// delegates must be the same of the methods
public delegate void addTwoNumbers(int a, int b);
public delegate void substractTwoNumbers(int a, int b);

// Method sumOf2Nums having same return type
// and parameter type as that of delegate
public void sumOf2Nums(int a, int b)
{
Console.WriteLine("({0} + {1}) = {2}", a, b, a + b);
}

// Method differenceOf2Nums having same return type
// and parameter type as that of delegate
public void differenceOf2Nums(int a, int b)
{
Console.WriteLine("({0} - {1}) = {2}", a, b, a - b);
}

// Main Method
public static void Main(String []args)
{

// Creating object of class "DelegateExampleClass"
DelegateExampleClass obj = new DelegateExampleClass();

// creating object of delegate, name as "del_obj1"
// for method "sum" and "del_obj2" for method "subtract" &
// pass the parameter as the two methods by class object "obj"
// instantiating the delegates

// Create objects of declared Delegates and pass
// the methods of class DelegateExampleClass
// using the objects thereby implementing Encapsulation
addTwoNumbers delegateObj1 = new addTwoNumbers(obj.sumOf2Nums);
substractTwoNumbers delegateObj2 = new substractTwoNumbers(obj.differenceOf2Nums);

// Call the methods of the class DelegateExampleClass
// using the delegate objects using appropriate values
delegateObj1(50, 40);
delegateObj2(50, 40);
}
}
}

Delegates in C# are similar to function pointers in C/C++ and can be used to pass methods as arguments to other methods, chained together, or even can be used to call methods on events.




Discussion

No Comment Found