Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

C# - What is Delegates in C# Example | Use of Delegates in C#

Sep 20, 2013
Introduction:

Here I will explain what is delegates in c#.net with example. Basically delegates in c# are type safe objects which are used to hold reference of one or more methods in c#.net. Delegates concept will match with pointer concept of c language.  

Description:


Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.

Syntax of Delegate & Methods Declaration

Check below sample code for delegate declaration and methods declaration


public delegate int Delegatmethod(int a,int b);

public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x + y;
}
}
If you observe above code I declared Delegatmethod method with two parameters which matching with methods declared in Sampleclass class.

Complete Example


public delegate int DelegatSample(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();

DelegatSample delgate1 = sc.Add;
int i = delgate1(10, 20);
Console.WriteLine(i);
DelegatSample delgate2 = sc.Sub;
int j = delgate2(20, 10);
Console.WriteLine(j);
}
}
Output

Whenever we run above code we will get output like as shown below


Add Result : 30
Sub Result : 10
What is the use of Delegates?

Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.

Delegates are two types

      -   Single Cast Delegates
      -  Multi Cast Delegates

Single Cast Delegates

Single cast delegate means which hold address of single method like as explained in above example.

Multicast Delegates

Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=

Multicast delegates will work only for the methods which have return type only void. If we want to create a multicast delegate with return type we will get the return type of last method in the invocation list

Check below sample code for delegate declaration and methods declaration

Syntax of Multicast Delegate & Method Declaration

Check below sample code for multicast delegate declaration and methods declaration


public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
If you observe above code I declared MultiDelegate method with void return type.

Complete Example


public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}
Output

Whenever we run above code we will get output like as shown below


Addition Value : 15
Subtraction Value : 5
Multiply Value : 50
I hope this post helps you to understand delegates in c#. Happy coding….

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

43 comments :

Unknown said...

Nice theory....with example..

I think here is a small mistake (the example of multicast delegate is replaced by single cast delegate....)...

plz look into this....

By the way nice blog to understand concept....!!!

Unknown said...

Very nice article and check for the example of multicast

Unknown said...

An easy way to understand the concept of Delegates.

As @Krishnat said, the example for multicast delegate is same as the single cast delegate.

Please see to it.

Thanks for the article.

Unknown said...

multicast example is same as single cast

Suresh Dasari said...

Thanks All for notify my error. Now the post updated Check it once and let me know if any problem is there.

Anonymous said...

Please add fb sharing feature in your blog.

Arun said...

Hi Suresh,
Regularly i am view your articles it's very much helpful. I have one doubt regarding gridview,when we load around 1000+ records in grid view other controls events not firing when we load 500+ records in same grid events are firing. How to solve this problem? pls suggests me.

Thanks,
Arunkumar.G


Anonymous said...

great work

Anonymous said...

Chaala baaga explain chesaav suresh.. Thank you..:-)

Unknown said...

where would we check the Upadated code mr.Suresh....

Anonymous said...

hi suresh,
ur explations are nice and easy to understand .but why ur not updating topics like wcf and mvc

Renuka @ said...

hi Suresh,
its really nice to understand Thanks a lot and pls will you explain topic like wcf and mvc

T.R.Bala said...

Hi.......Thank you very much for this nice example.

Anonymous said...

simplified neat exapmle..good work, thx.

Anonymous said...

very easy desc to understand the concept...

Anonymous said...

Actually I bought reference book for .Net but Delegates topic was poorly explained in it, I was beating my self up for it, then I stumbled upon your blog. Very simple and easy to understand examples, finally I now understand delegates.

Thanks,
Suresh

dimple Bhendarkar said...

thank you..!
explanation is very effective for C# learner like me

Anonymous said...

Nice Article...

Anonymous said...

Hi Suresh,
Thanks for this very good article, I have a confusion here please elaborate this.
'Multicast delegates will work only for the methods which have return type only void'. Please elaborate this.
Thanks
Regards
Asif Aslam

Anonymous said...

Simple and Nice explanation.

TARESH said...

Hello Mr.Suresh Thanks For This Nice Article.But I have a problem....Plz Solve My Problem ......using System;
public delegate int mydelegate(int a, int b);
class func
{
public int add(int x, int y)
{
return x + y;
}
public int sub(int x, int y)
{
return x - y;
}
public static void Main()
{
func obj = new func();
mydelegate delegate1 = obj.add;
int i = delegate1(10, 20);
Console.WriteLine(i);
mydelegate delegate2 = obj.sub;
int j = delegate2(20, 10);
Console.WriteLine(j);
Console.ReadLine();

}
}




using System;
class overload
{
public int add(int a, int b)
{
return a + b;

}
public int sub(int a, int b)
{
return a - b;
}
public static void Main()
{
overload obj1 = new overload();
int i = obj1.add(10,20);
Console.WriteLine(i);
int j = obj1.sub(20,10);
Console.WriteLine(j);
Console.ReadLine();
}
}

What Is The Different Between Code........Use of Delegate and Other....

Anonymous said...

nice article to understand the concept of delegate.. thank you

Anonymous said...

Good article.Short but sweet...

Anonymous said...

Amazing article to learn what is delegate..thnk..

Unknown said...

waw, to easy explanation you are such a genius yar

Anonymous said...

public delegate int mydelegate(int a, int b);
class func
{
public int add(int x, int y)
{
return x + y;
}
public int sub(int x, int y)
{
return x - y;
}
public static void Main()
{
func obj = new func();
mydelegate delegate1 = obj.add;
int i = delegate1(10, 20);
Console.WriteLine(i);
mydelegate delegate2 = obj.sub;
int j = delegate2(20, 10);
Console.WriteLine(j);
Console.ReadLine();

}
}




using System;
class overload
{
public int add(int a, int b)
{
return a + b;

}
public int sub(int a, int b)
{
return a - b;
}
public static void Main()
{
overload obj1 = new overload();
int i = obj1.add(10,20);
Console.WriteLine(i);
int j = obj1.sub(20,10);
Console.WriteLine(j);
Console.ReadLine();
}
}

What Is The Different Between Code........Use of Delegate and Other....

Anonymous said...

good work dude.

Anonymous said...

Good article...helped alot..thank you:)

Ratnesh tiwari said...

nice sir ji.................

INDIAN said...

Come on Guys! All of you successfully complicated the DELEGATES :)!

I will try to leave a hint here : i understood delegates once I realized jquery ajax calls in Javascript. for ex: ajax.send(url, data, successcallback, failcallback) is the signature of the function. as you know, it sends data to the server URL, as a response, It might be 200OK or some other error. In case of any such event(success/fail), you want to execute a function. So, this acts like a placeholder of a function, to be able to mention in either success or failure.
That placeholder may not be very generic - it might accept a set of parameters and may/may not return value. That declaration of such Placeholder, if done in C# IS CALLED DELEGATE! As javascript functions not strict with number of arguments, you would just see them as GENERIC placeholders...but C# has some STRICT declarations... that boils down to DELEGATE declarations!!

Hope it helps!

Anonymous said...

@INDIAN..
be indian and don't be oversmart..

by the way very nice explanation an very good example @Suresh Dasari

Anonymous said...

class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}
in above code why did u use class name to call the method(Sampleclass.Add) instead of it's object , since Sampleclass is not a static class?

Unknown said...

Superb

Unknown said...

Hi Suresh,

Thanks for your valuable post. it is very useful for me and please share more samples regarding the explained concept

Anonymous said...

nice example

Unknown said...

nice example thnks

Unknown said...

Please correct the following line.
"Multicast delegates will work only for the methods which have return type only void."

Manoranjan Behera said...

So Nice

Gourav Bhatt said...

Awesome now i have understand the concept of Delegates. thank a lot

Unknown said...

Very good article

Anonymous said...

Greate Explanation.

Unknown said...

super ..

Unknown said...

nice theory with examples...

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.