What are "Delegates" in C#

SheoNarayan
Posted by in C# category on for Beginner level | Points: 250 | Views : 39119 red flag
Rating: 4 out of 5  
 4 vote(s)

Delegates, a word that frequently pops up in the Interviews and many candidates gets confused and nervous when they hear this word. In this article, I am trying to explain delegates in easy to understand way, hopefully after going through this article, you will feel comfortable using delegates and answering any question related with delegates.

What is a delegate?


Delegate is an object that can refer to a method.

When we are creating delegates, we are creating an object that can hold a reference to a method; it necessarily means that a delegate can invoke the method to which it refers. 

As the delegate refers to a method, the same delegates can be used to call multiple methods just by changing the method name at the run time; provided the method (instance or static) match the signature and return type.

Get my 500+ Web development .NET Tips & Tricks and avail ASP.NET online training here.

Confused? not a problem, just go through below code snippet of code behind (DelegatesPage 
.aspx.cs) of my DelegatesPage.aspx page.

public partial class DelegatesPage : System.Web.UI.Page

{

delegate int Add(int x);

protected void Page_Load(object sender, EventArgs e)

{

Add a = Sum;

Response.Write(a(6).ToString());

Response.Write("<br />");

a = Minus;

Response.Write(a(6).ToString());

}

 

int Sum(int a)

{

return a + a;

}

 

int Minus(int b)

{

return b - b;

}

}

In the above code snippet, we have declared a delegates named Add that accepts one parameter of integer type. In the Page_Load event, we are assigned Sum method (we will define & implement this method later on) to the delegates object "a". That means that now a can be used to invoke the Sum method. In the very next line, we used "a" that is nothing but the object of delegate Add to call the Sum method. As the Sum method accepts one parameter so we are calling "a" with one parameter "6".

As the Sum method simply add the values are return so calling "a(6)" will return 12.

As I said earlier, the delegate simply refers a method so the same delegate can be used to refer another method and next I have referred Minus method (defined and implemented later on) and again we are calling Minus method just by using the delegate object that gives 0 result.


What is Multicast delegates?


As the name suggest (Multicast), it means multiple so A delegate that refers multiple methods is called Multicast delegates. Calling the object of the delegates automatically call all method referred to this delegate. These methods can be attached and detached using "+=" and "-=" to the instance of the delegate.

In case a delegate returns a value (as in the case of above delegate), the value returned by last method becomes the return value of the entire delegate invocation methods.

public partial class DelegatesPage : System.Web.UI.Page

{

// multi-cast delegates

delegate void Add(int x);

protected void Page_Load(object sender, EventArgs e)

{

Add a = Sum;

a += Minus;

a(6);

}

 

void Sum(int a)

{

Response.Write(a + a);

Response.Write("<br />");

}

 

void Minus(int b)

{

Response.Write(b - b);

}

}


In the above code snippet, as you can see that we have a Delegate named "Add" that accepts two parameter but does not return any value as it is void.

In the Page_Load event, we have created the object of the delegate and assigned Sum method; in the very next line we have attached one more method called Minus to the same delegates using "+=" operator.

Now calling the delegates object, simply executes both Sum and Minus method and gives respective results. So we will get 12 and 0 result.  If you have consumed WCF services, you must have came across multicast delegates scenario.


When to use Delegates?


All this looks fine, now the important question is why and when to use delegates? As per MSDN

Use a delegate when:
  • An eventing design pattern is used.
  • It is desirable to encapsulate a static method.
  • The caller has no need access other properties, methods, or interfaces on the object implementing the method.
  • Easy composition is desired.
  • A class may need more than one implementation of the method.
Sounds complicated? In simple term Delegates are basically used in
  1. Abstracting and encapsulating methods
  2. Callback mechanism
  3. Asynchronous programming
  4. Sequential programming etc.
below are some more links that help you understand Delegates and in which scenario to use delegates


Hope this article would be helpful in understanding Delegates.

Thanks for reading, keep reading and sharing your knowledge.

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Biswarup90 on: 11/23/2011 | Points: 25
Delegate in C#

What is Delegate?
Delegate is type which holds the method(s) reference in an object. It is also reffered as a type safe function pointers.

Advantages:

Encapsulating the method's call from caller.
Effective use of Delegat improves the performance of application.
Used to call a method asynchronously.

Declaration of Delegate

public delegate type_of_delegate delegate_name()

Example : public delegate int testdelegate(int delegate variable1,int delegate variable2)

Importan point in Delegate

you can use delegeate without parameter or with parameter list.
you should follow the same syntax as in the method.

(if you are reffering the method with two int parameters and int return type the delegate which you are declaring should be the same format.This is how it is reffered as type safe function pointer)

Declaring and Implementing a Delegate: SimpleDelegate.cs

using System; (namespace)

// this is the simple delegate declaration
public delegate int Comparer(object obj1, object obj2);

public class Name
{
public string FirstName = null;//
public string LastName = null;

public Name(string first, string last)
{
FirstName = first;
LastName = last;
}

// this is the delegate method handler
public static int CompareFirstNames(object name1, object name2)
{
string n1 = ((Name)name1).FirstName;
string n2 = ((Name)name2).FirstName;

if (String.Compare(n1, n2) > 0)
{
return 1;
}
else if (String.Compare(n1, n2) < 0)
{
return -1;
}
else
{
return 0;
}
}

public override string ToString()
{
return FirstName + " " + LastName;
}
}

class SimpleDelegate
{
Name[] names = new Name[5];

public SimpleDelegate()
{
names[0] = new Name("Joe", "Mayo");
names[1] = new Name("John", "Hancock");
names[2] = new Name("Jane", "Doe");
names[3] = new Name("John", "Doe");
names[4] = new Name("Jack", "Smith");
}

static void Main(string[] args)
{
SimpleDelegate sd = new SimpleDelegate();

// this is the delegate instantiation
Comparer cmp = new Comparer(Name.CompareFirstNames);

Console.WriteLine("\nBefore Sort: \n");

sd.PrintNames();

// observe the delegate argument
sd.Sort(cmp);

Console.WriteLine("\nAfter Sort: \n");

sd.PrintNames();
}

// observe the delegate parameter
public void Sort(Comparer compare)
{
object temp;

for (int i=0; i < names.Length; i++)
{
for (int j=i; j < names.Length; j++)
{
// using delegate "compare" just like
// a normal method
if ( compare(names[i], names[j]) > 0 )
{
temp = names[i];
names[i] = names[j];
names[j] = (Name)temp;
}
}
}
}

public void PrintNames()
{
Console.WriteLine("Names: \n");

foreach (Name name in names)
{
Console.WriteLine(name.ToString());
}
}
}


Multicast Delegate :

Delegates which hold and invoke multiple methods are known as multicast delegates. But simple delegates invoke only one method. Multicast delegates must satisfy the following condition:

· The return type of the delegate must void.

· None of the parameters of the delegate type can be declared as output parameters, using out keywords.


For Example:

delegate void Multidelegate();

class Program

{

public static void Main()

{

Multidelegate mshow1 = new Multidelegate(Class1.show1);

Multidelegate mshow2 = new Multidelegate(Class1.show2);

Multidelegate mshow3 = mshow1 - mshow2;

Multidelegate mshow4 = mshow2 - mshow1;

Multidelegate mshow5 = mshow3 - mshow2;

Multidelegate mshow6= mshow5 - mshow4;

mshow3();

mshow4();

mshow5();

mshow6();

Console.ReadLine();

}

}

class Class1

{

static public void show1()

{

Console.WriteLine("Biswa");

}

static public void show2()

{

Console.WriteLine("Sourav");

}

}

Output:

Biswa

Sourav

Biswa

Biswa
Posted by: Nerdanalysis on: 11/24/2011 | Points: 25
Thanks for the article. What does it mean type safe function pointer ?
Posted by: Rajesh081725 on: 12/7/2012 | Points: 25
Hi all,

Can u tell me

Why delegate are used in c#
What is ths use of delegate
can u give real time example.

Login to post response

Comment using Facebook(Author doesn't get notification)