Delegates in C# – Part 1

In a simple term a delegate is a pointer to function. Or in more simpler terms, delegate is a reference to a method and it is provides a mechanism to call a method through its reference (delegate) or to pass a method as argument to another method.
Simple example of delegate:

//Declaration of delegate type
public delegate int TaskPerformer(Employee e); // Here Employee is some class
public class Employee
{
//Define some data members and methods
}
public class SomeClass
{
public int SomeMethod(Employee e)
{
int i = 0;
//Perform some task
Console.WriteLine("SomeMethod is called");
return i;
}
}
public class SomeOtherClass
{
public static void Main(string[] args)
{
SomeClass obj = new SomeClass();
Employee e = new Employee();

//Create instance of delegate type
TaskPerformer tp = new TaskPerformer(obj.SomeMethod);

//Call method using delegate
tp(e);

//Above statement will do the same job as below statement, but above statement calls method using delegate.
//obj .SomeMethod(e);

Console.ReadLine();
}
}

Clarity on terminology: Delegate is a C# type. Term ‘Delegate’ is used for both type and instance of type.

Above example is simplest demonstration of delegate, whereas purpose of delegate is more than just calling a method.

For better understanding of delegates you should understand the concept of polymorphism.
As with concept of polymorphism, base class instance refers a child class instance and at runtime behaviour gets changed based on the fact that base class refers to which child class instance.
Same benefit we get with delegates. At runtime it’s found that which method is referenced by delegate instance and accordingly behaviour gets changed.

Please refer another post Delegates in C# – Part 2, where we will talk about different ways of writing delegates in C#.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s