Congratulations to all the winners of April 2013, they have won INR 3400 cash and INR 20147 worth prizes !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 19567 |  Welcome, Guest!   Register  Login
Home > Articles > C# > What are "Delegates" in C#

What are "Delegates" in C#

4 vote(s)
Rating: 4 out of 5
Article posted by SheoNarayan on 11/19/2011 | Views: 22297 | Category: C# | Level: Beginner | Points: 250 red flag


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.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

 Responses
Posted by: Biswarup90 | Posted on: 23 Nov 2011 01:06:17 AM | 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, names[j]) > 0 )
{
temp = names;
names = 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 | Posted on: 24 Nov 2011 07:22:42 PM | Points: 25

Thanks for the article. What does it mean type safe function pointer ?

Posted by: Gaur1982 | Posted on: 30 Apr 2012 05:28:17 AM | Points: 25

Read more about C# Delegates on this URL : http://planetofcoders.com/c-delegates/

Posted by: Rajesh081725 | Posted on: 07 Dec 2012 07:16:59 AM | 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.

>> Write Response - Respond to this post and get points
Related Posts

In a simple words Constructor is nothing but a method, a special kind of method of a class, which gets executed when its (class) object is created. Now, let’s take above in broader sense, a constructor is a class method automatically executed whenever class’s object is created or whenever class is initialized

In this article we will read trx file by using Linq to XML

Generally in many websites after you get logged in you will be redirected to home page. While this page is running if the user selects the new window and open the Login page again and if he provides the same credentials which was provided earlier then he will be automatically redirected to home page. But in this article I am going to explain how to restrict this if you consider the examples of gmail.com or yahoo.com once in a particular user is logged in they won’t restrict the user but here I will provide that feature and check whether if a particular user is logged in I will display it as already logged in.

You may wonder about the idea of calling this DLL in a C# Application. Well, the C# language provides a way to call this COM server in a program. When we compile a C# program, Intermediate Language is generated and it is called as Managed Code. A Visual Basic 6.0 DLL is Unmanaged, meaning it is not generated by the Common Language Runtime, but we can make this VB DLL interoperate with C#, by converting it into a .NET compatible version. The following example shows how to create a simple server by using Visual Basic 6.0 and implementing it in a C# client program.

This article is inspired to present the easiest way of building your own speech to text based call recording system.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/19/2013 4:06:05 PM