What are the benefits/advantages of using delegates? Can anyone provide any simple examples?
-
Advantages of delegates in comparison to what? – Mehrdad Afshari Mar 12 '09 at 16:07
-
Are there any alternatives in .Net used by more than 10 people? – mmmmmmmm Mar 12 '09 at 17:07
-
1In comparison to not using delegates. which would lead to intensely coupled, incredibly difficult code. – DevinB Mar 12 '09 at 20:29
-
From C# 6.0 in a Nutshell: A delegate instance literally acts as a delegate for the caller: the caller invokes the delegate, and then the delegate calls the target method. This indirection decouples the caller from the target method. – user2330678 Feb 08 '16 at 00:28
7 Answers
They're a great way of encapsulating a piece of code. For instance, when you attach an event handler to the button, that handler is a delegate. The button doesn't need to know what it does, just how to call it at the right time.
Another example is LINQ - filtering, projecting etc all require the same kind of template code; all that changes is the logic to represent the filter, the projection etc. With lambda expressions in C# 3 (which are converted into delegates or expression trees) this makes it really simple:
var namesOfAdults = people.Where(person => person.Age >= 18)
.Select(person => person.Name);
(That can also be represented as a query expression, but let's not stray too far from delegates.)
Another way of thinking of a delegate is as a single-method interface type. For example, the EventHandler
delegate type is a bit like:
public interface IEventHandler
{
void Invoke(object sender, EventArgs e)
}
But the delegate support in the framework allows delegates to be chained together, invoked asynchronously, used as event handlers etc.
For more on delegates and events, see my article on the topic. Its focus is events, but it covers delegates too.

- 1,421,763
- 867
- 9,128
- 9,194
-
Thanks John. As a beginner, it is still a little hard to grasp. Sometimes, I think I need to do it the old way before delegates came along to really see the true advantage. – Xaisoft Mar 12 '09 at 16:18
-
@Xaisoft: Don't worry :) And yes, it can be a little hard to grasp. But it comes over time - and then you wonder what you did before delegates came along, particularly with lambda expressions... – Jon Skeet Mar 12 '09 at 16:28
-
Also, for beginners, it's important to realize that delegates don't let you do anything you couldn't do otherwise. It just makes it easier and cleaner (if not abused). Delegates themselves have undergone two revisions since .Net 1.0, and are much more concise now compared to their original form. – Michael Meadows Mar 12 '09 at 16:48
-
@JonSkeet - can you kindly explain the first paragraph with an example. I could not understand it. **"They're a great way of encapsulating a piece of code. For instance, when you attach an event handler to the button, that handler is a delegate. The button doesn't need to know what it does, just how to call it at the right time."** – Aug 05 '12 at 08:09
-
@RGI: Which bit of the first paragraph? Did you read the article linked in the final paragraph? It goes into a lot more detail. – Jon Skeet Aug 05 '12 at 08:09
-
Sorry, I am looking into it. If you don;t mind can i continue here if find any confusion? – Aug 05 '12 at 08:10
-
@RGI: It may be clearer to ask a new question with the specific areas involved, ideally having tried the ideas out in code (and including the code in the question). – Jon Skeet Aug 05 '12 at 08:11
-
-
@JonSkeet I think you just crossed 1000K so new machnisim is required to display it :) – Arijit Mukherjee Jan 16 '18 at 06:39
This is a pretty vague topic, but here are a few things to consider -
Delegates are basically a cleaner, easier function pointer. Any place where function pointers were used in C++, you can think delegate.
Advantages to using them in design:
- Can lead to easy reuse of code
- Can provide a great amount of flexibility in your designs
- Allow you to develop libraries and classes that are easily extensible, since it provides an easy way to hook in other functionality (for example, a where clause in LINQ can use a delegate
[Func<T,bool>]
to filter on, without having to write new code in the Where method
Potential disadvantages:
- They
~can~
, particularly if used naively, lead to code that is more difficult to read - They can introduce behavior into your component that is unexpected, since 3rd party code out of your control will get called (For example, if somebody attaches a delegate to one of your events that causes an infinite loop, it can make your class look bad, even though it has nothing to do with you)

- 6,002
- 2
- 24
- 39

- 554,122
- 78
- 1,158
- 1,373
-
Although Reed Copsey gives his answer in the specific language of C++ it is important for all those who like to know "Why" the value of his answer here. Keep in mind that every virtual machine needs to be written to the machines they run on. This holds for Java and .Net. The JVM in Java and the CLR in .Net (the engines that run your code written in Java, C#, VB, etc.) are written in C code (C/C++). So when Reed says that delegates are basically a cleaner function pointer this applies to all the 'easier to manage' languages that are abstracted from the underlying C based engine. – Zack Jannsen Sep 16 '13 at 11:38
Delegates serve three purposes:
- A simplified implementation of the Observer pattern
- A simplified implementation of callbacks
- Anonymous (non-reusable) blocks of code
Observer
public class Something
{
public event EventHandler SomethingHappened;
}
public class SomethingConsumer
{
private mySomething = new Something();
public void WireUpEvents()
{
mySomething.SomethingHappened += whenSomethingHappened;
}
private void whenSoemthingHappened(object sender, EventArgs e)
{
// do something
}
}
CallBack
public void DoSomethingAsynchronously(EventHandler callBack)
{
// long running logic.
callBack(this, EventArgs.Empty);
}
Anonymous non-reusable code
public void DoSomethingReusably(Action nonReusableCode)
{
// reusable code
nonReusableCode();
// more reusable code
}
public void DoALotOfSomething()
{
DoSomethingReusably(() => { /* non-reusable code here */ });
DoSomethingReusably(() => { /* non-reusable code here */ });
DoSomethingReusably(() => { /* non-reusable code here */ });
}
In all cases, it's just a matter of providing conciceness.

- 27,796
- 4
- 47
- 63
Delegate in C# is eqv. to function pointer in C, but it also carries a reference to the class instance that it was created from.
All event handlers in Windows Forms are delegates.

- 40,822
- 8
- 72
- 132
Advantages compared to what? Delegates can be useful things, and surely have their place in a lot of moderately complex C# code. (Whenever you use events in classes you are implicitly using multicast delegates). If you want an introduction to their syntax and uses, I recommend the following articles:

- 144,213
- 56
- 264
- 302
-
-
Oh, I see. Well in C# you don't really have a choice of alternatives. There's no point in using them for the same purpose as events (although it can be done of course). You typically don't use real pointers, as that requires unsafe code, which is considered bad practice and leads to security issues. – Noldorin Mar 12 '09 at 16:21
-
@Noldorin I may be misunderstanding your comment, but events use delegates. It's transparent, but it does occur. – Michael Meadows Mar 12 '09 at 16:50
-
@Michael: Yeah, that comment was slightly confusing on second look. Events are indeed multicast delegates with syntactic sugar for the most part (plus a few other differences, which have been discussed in other threads). I think I wrote that delegates are implicitly used but then deleted that bit :P – Noldorin Mar 12 '09 at 17:00
Disclaimer: I'm not saying how I used a delegate is the intended way but it is an example.
I've only used it once before but basically in our app the user clicks a 'Complete' button for a step which then takes them to a routing page to decide where to send it next. So technically the step they just clicked 'Complete' on isn't really finished until they route it. But since I'm on another page I didn't easily have access to where they just were.
So what I did was created a delegate for the few steps that required special processing (in this case an email) when the clicked 'Complete', and when they routed it on the next page I would check for the existance of the delegate and if it was there call it to fire my 'stored' event.
Creative: probably, wrong: maybe, working: definately.
Like I said probably not how it was intended to be used, but coding is as much art as science right?

- 4,278
- 5
- 30
- 49
I remember an early Java GUI framework that had no concept of delegates or command routing. In order to make a button that does something, you had to subclass Button and override the click method. You ended up with lots and lots of UI element subclasses with little bits of your application code in them.
The code that handles that click has to go somewhere, and in an OO language like Java or C# it has to go on a class, but delegates allow it to happen on convenient place. That often leads to having too much code doing too many different things in a form class, but that's a different issue.

- 5,176
- 6
- 65
- 87