Delegates is a type used to hold a reference
of method in an object. Delegates can also be referred as a pointer to function.
Delegates are similar to function pointer in c#.
Syntax of Declaration of Delegates:
Public delegate type_of_delegate delegate_name( );
Example
public
delegate void
d();
Note
Delegate may contain any number of argument or it may be without any parameter
list.
Syntax of Creating Instance of Delegate:
public delegate_name name_of_instance;
Example
public d obj;
Program
using System;
namespace del
{
class Program
{
public delegate int d(int a);
public static d obj;
public static int method(int i)
{
Console.WriteLine("Creating Method");
return i;
}
static void Main(string[] args)
{
int n;
obj = new d(method);
n = obj(8);
Console.WriteLine("value called via delegate is "+n);
Console.ReadLine();
}
}
}
Output
Description of above Program
- In the above program The Delegate "d" is declared with int return type having one parameter.
- After that the delegate instance "obj" is
created and then a method is created.
Note - Following Syntax should be followed (if you are declaring a method of int type having one parameter of type int, then delegate which you are declaring should be in same format this is the reason it is called type safe reason)
- In main method the method name is passed
to delegate instance.
obj = new d(method);
Multicast Delegate
Multicast Delegate is a Delegate which hold the reference of more than one
method.
Note- Multicast Delegate must contain method that returns void.
Program
using System;
namespace del
{
class Program
{
public delegate void d(int a,int b);
public static d obj;
public static void sum(int i, int i1)
{
int c;
c = i + i1;
Console.WriteLine("Creating Method 1 and value is "+c);
}
public static void mul(int i,int i1)
{
int c;
c = i * i1;
Console.WriteLine("Creating Method 2 and value is " + c);




Pravin KumarPosted Apr 9, 2017, 3:29 AM
function pointer in c#?
Abhishek GuptaPosted Sep 8, 2014, 9:30 AM
Nice one