Delegates in C#
Up Java Resources C++ Resources Comp410

A delegate in C# allows us to pass methods of one class to objects of another classes that can call these methods. We can pass both static and instance methods. This concept is familiar to C++  function pointers which are used to pass functions as parameters to other methods in the same class or in another class.

Let us consider a simple example :

class Example
{
	delegate void eg1();
	delegate void eg2 (int i);
	public void example()
	{
		eg1 d1 = new eg1 (fun1);
		d1();
		eg2 d2 = new eg2 (fun2) ;
		d2 ( 5 ) ;
	}
	public void fun1()
	{
		Console.WriteLine (“Reached fun1”) ;
	}
	public void fun2 (int i)
	{
		Console.WriteLine (“Reached fun2”) ;
	}
}

In the above class, we have declared two delegates, eg1 and eg2. The statement delegate void eg1( ) ;
indicates that the delegate eg1 is going to encapsulate methods, which takes no parameter and returns void.

The statement eg1 d1 = new eg1 ( fun1 ) ;

would create a delegate object d1. To the constructor of the delegate class we have passed the address of the method fun1( ).  The delegate object would now hold an address of the method fun1( ). Next, we have called the fun1( ) method using the delegate object d1. This is achieved using the statement d1( ) ;

The same explanation holds for the delegate eg2, with the difference that the method encapsulated, fun2(), takes an integer argument.