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:
In
previous posts I explained OOPS examples in c#, polymorphism in c#, Difference b/w datareader, dataset and
dataadapter in c#, Difference b/w appsettings and
connection strings in asp.net, Difference b/w executereader,
executenonquery and executescalar in c# and many articles
relating to
interview questions in c#,
asp.net,
sql server, javascript,
jquery. Now I will explain delegates
in c#.net with example.
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. |
|||
|
|||
43 comments :
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....!!!
Very nice article and check for the example of multicast
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.
multicast example is same as single cast
Thanks All for notify my error. Now the post updated Check it once and let me know if any problem is there.
Please add fb sharing feature in your blog.
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
great work
Chaala baaga explain chesaav suresh.. Thank you..:-)
where would we check the Upadated code mr.Suresh....
hi suresh,
ur explations are nice and easy to understand .but why ur not updating topics like wcf and mvc
hi Suresh,
its really nice to understand Thanks a lot and pls will you explain topic like wcf and mvc
Hi.......Thank you very much for this nice example.
simplified neat exapmle..good work, thx.
very easy desc to understand the concept...
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
thank you..!
explanation is very effective for C# learner like me
Nice Article...
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
Simple and Nice explanation.
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....
nice article to understand the concept of delegate.. thank you
Good article.Short but sweet...
Amazing article to learn what is delegate..thnk..
waw, to easy explanation you are such a genius yar
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....
good work dude.
Good article...helped alot..thank you:)
nice sir ji.................
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!
@INDIAN..
be indian and don't be oversmart..
by the way very nice explanation an very good example @Suresh Dasari
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?
Superb
Hi Suresh,
Thanks for your valuable post. it is very useful for me and please share more samples regarding the explained concept
nice example
nice example thnks
Please correct the following line.
"Multicast delegates will work only for the methods which have return type only void."
So Nice
Awesome now i have understand the concept of Delegates. thank a lot
Very good article
Greate Explanation.
super ..
nice theory with examples...
Note: Only a member of this blog may post a comment.