What are your usage of delegates in C#?
-
2Do you mean delegates in the .NET type system or the C# delegate syntax? Do you mean "when do you use the delegate syntax instead of lambda expression syntax" or do you mean "when do you use delegates instead of classes/interfaces/virtual methods/etc."? – Niki Aug 01 '09 at 12:36
-
[http://stackoverflow.com/questions/1137431/are-net-delegates-used-for-events](http://stackoverflow.com/questions/1137431/are-net-delegates-used-for-events) – Raghav Aug 05 '09 at 14:07
20 Answers
Now that we have lambda expressions and anonymous methods in C#, I use delegates much more. In C# 1, where you always had to have a separate method to implement the logic, using a delegate often didn't make sense. These days I use delegates for:
- Event handlers (for GUI and more)
- Starting threads
- Callbacks (e.g. for async APIs)
- LINQ and similar (List.Find etc)
- Anywhere else where I want to effectively apply "template" code with some specialized logic inside (where the delegate provides the specialization)

- 1,421,763
- 867
- 9,128
- 9,194
-
-
3Not sure how I'd explain it briefly without making things more confusing :) (Arguably it's covered by event handlers, LINQ, and the templaty bit anyway! – Jon Skeet Oct 10 '08 at 13:55
-
1
-
-
3I know what you're trying to say, but I would find the following easier to read: "Now that we have lambda expressions and anonymous methods in C#, I use delegates much more." I know I'm nitpicking, but I really had to read that sentence a few times before it made sense to me. – senfo Feb 19 '09 at 15:44
-
4
-
Delegates are very useful for many purposes.
One such purpose is to use them for filtering sequences of data. In this instance you would use a predicate delegate which accepts one argument and returns true or false depending on the implementation of the delegate itself.
Here is a silly example - I am sure you can extrapolate something more useful out of this:
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<String> names = new List<String>
{
"Nicole Hare",
"Michael Hare",
"Joe Hare",
"Sammy Hare",
"George Washington",
};
// Here I am passing "inMyFamily" to the "Where" extension method
// on my List<String>. The C# compiler automatically creates
// a delegate instance for me.
IEnumerable<String> myFamily = names.Where(inMyFamily);
foreach (String name in myFamily)
Console.WriteLine(name);
}
static Boolean inMyFamily(String name)
{
return name.EndsWith("Hare");
}
}

- 344,730
- 71
- 640
- 635
-
11The `static Boolean inMyFamily(String name)` method is the delegate. Where takes a delegate as a parameter. Since delegates are just function pointers when you pass the method name into the `.Where(delegate)` that becomes the delegate. Since inMyFamily returns a boolean type it is actually considered a predicate. Predicates are just delegates that return booleans. – Landon Poch Aug 22 '12 at 15:18
-
4
-
@LandonPoch that comment would have been better placed in the answer. me being a beginner couldn't make out where it was. thanks. – Eakan Gopalakrishnan Sep 03 '14 at 22:16
-
@Eakan, I wasn't really answering the main question (when would you use delegates) so I left it as a comment instead. – Landon Poch Sep 04 '14 at 18:09
Found another interesting answer:
A coworker just asked me this question - what's the point of delegates in .NET? My answer was very short and one that he had not found online: to delay execution of a method.
Source: LosTechies
Just like LINQ is doing.

- 13,614
- 9
- 57
- 107
Delegates can often be used in place of an interface with one method, a common example of this would be the observer pattern. In other languages if you want to receive a notification that something has happened you might define something like:
class IObserver{ void Notify(...); }
In C# this is more commonly expressed using events, where the handler is a delegate, for example:
myObject.SomeEvent += delegate{ Console.WriteLine("..."); };
Another great place to use delegates if when you have to pass a predicate into a function, for example when selecting a set of items from a list:
myList.Where(i => i > 10);
The above is an example of the lambda syntax, which could also have been written as follows:
myList.Where(delegate(int i){ return i > 10; });
Another place where it can be useful to use delegates is to register factory functions, for example:
myFactory.RegisterFactory(Widgets.Foo, () => new FooWidget());
var widget = myFactory.BuildWidget(Widgets.Foo);
I hope this helps!

- 28,019
- 8
- 80
- 108
You can use delegates to declare function-typed variables and parameters.
Example
Consider the "resource borrowing" pattern. You want to control the creation and cleanup of a resource, while allowing client code to "borrow" the resource in between.
This declares a delegate type.
public delegate void DataReaderUser( System.Data.IDataReader dataReader );
Any method matching this signature can be used to instantiate a delegate of this type. In C# 2.0, this can be done implicitly, simply by using method's name, as well as by using anonymous methods.
This method uses the type as a parameter. Note the delegate's invocation.
public class DataProvider
{
protected string _connectionString;
public DataProvider( string psConnectionString )
{
_connectionString = psConnectionString;
}
public void UseReader( string psSELECT, DataReaderUser readerUser )
{
using ( SqlConnection connection = new SqlConnection( _connectionString ) )
try
{
SqlCommand command = new SqlCommand( psSELECT, connection );
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while ( reader.Read() )
readerUser( reader ); // the delegate is invoked
}
catch ( System.Exception ex )
{
// handle exception
throw ex;
}
}
}
The function can be called with an anonymous method as follows. Note that the anonymous method can use variables declared outside of itself. This is extremely handy (although the example is a little contrived).
string sTableName = "test";
string sQuery = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='" + sTableName + "'";
DataProvider.UseReader( sQuery,
delegate( System.Data.IDataReader reader )
{
Console.WriteLine( sTableName + "." + reader[0] );
} );

- 41,820
- 13
- 96
- 131
I'm coming in on this really late but I was having trouble figuring out the purpose of delegates today and wrote two simple programs that give the same output that I think explains their purpose well.
NoDelegates.cs
using System;
public class Test {
public const int MAX_VALUE = 255;
public const int MIN_VALUE = 10;
public static void checkInt(int a) {
Console.Write("checkInt result of {0}: ", a);
if (a < MAX_VALUE && a > MIN_VALUE)
Console.WriteLine("max and min value is valid");
else
Console.WriteLine("max and min value is not valid");
}
public static void checkMax(int a) {
Console.Write("checkMax result of {0}: ", a);
if (a < MAX_VALUE)
Console.WriteLine("max value is valid");
else
Console.WriteLine("max value is not valid");
}
public static void checkMin(int a) {
Console.Write("checkMin result of {0}: ", a);
if (a > MIN_VALUE)
Console.WriteLine("min value is valid");
else
Console.WriteLine("min value is not valid");
Console.WriteLine("");
}
}
public class Driver {
public static void Main(string [] args) {
Test.checkInt(1);
Test.checkMax(1);
Test.checkMin(1);
Test.checkInt(10);
Test.checkMax(10);
Test.checkMin(10);
Test.checkInt(20);
Test.checkMax(20);
Test.checkMin(20);
Test.checkInt(30);
Test.checkMax(30);
Test.checkMin(30);
Test.checkInt(254);
Test.checkMax(254);
Test.checkMin(254);
Test.checkInt(255);
Test.checkMax(255);
Test.checkMin(255);
Test.checkInt(256);
Test.checkMax(256);
Test.checkMin(256);
}
}
Delegates.cs
using System;
public delegate void Valid(int a);
public class Test {
public const int MAX_VALUE = 255;
public const int MIN_VALUE = 10;
public static void checkInt(int a) {
Console.Write("checkInt result of {0}: ", a);
if (a < MAX_VALUE && a > MIN_VALUE)
Console.WriteLine("max and min value is valid");
else
Console.WriteLine("max and min value is not valid");
}
public static void checkMax(int a) {
Console.Write("checkMax result of {0}: ", a);
if (a < MAX_VALUE)
Console.WriteLine("max value is valid");
else
Console.WriteLine("max value is not valid");
}
public static void checkMin(int a) {
Console.Write("checkMin result of {0}: ", a);
if (a > MIN_VALUE)
Console.WriteLine("min value is valid");
else
Console.WriteLine("min value is not valid");
Console.WriteLine("");
}
}
public class Driver {
public static void Main(string [] args) {
Valid v1 = new Valid(Test.checkInt);
v1 += new Valid(Test.checkMax);
v1 += new Valid(Test.checkMin);
v1(1);
v1(10);
v1(20);
v1(30);
v1(254);
v1(255);
v1(256);
}
}

- 1,491
- 1
- 19
- 28
Delegates are used any time you use events - that's the mechanism by which they work.
In addition, delegates are very useful for things such as using LINQ queries. For example, many LINQ queries take a delegate (often Func<T,TResult>
) which can be used for filtering.

- 554,122
- 78
- 1,158
- 1,373
A slightly different use is to speed up reflection; i.e. instead of using reflection each time, you can use Delegate.CreateDelegate
to create a (typed) delegate to a method (a MethodInfo
), and call that delegate instead. This is then much quicker per call, as the checks have already been done.
With Expression
, you can also do the same to create code on the fly - for example, you can easily create an Expression
that represents the + operator for a type chosen at runtime (to provide operator support for generics, which the language doesn't provide); and you can compile an Expression
to a typed delegate - job done.

- 1,026,079
- 266
- 2,566
- 2,900
An example might be as seen here. You have a method to process an object that meets certain requirements. However, you want to be able to process the object in multiple ways. Instead of having to create separate methods, you can simply assign a matching method that processes the object to a delegate and pass the delegate to the method that selects the objects. That way, you can assign different methods to the one selector method. I tried to make this easily understandable.

- 36,151
- 76
- 250
- 438

- 21
- 1
I use delegates to communicate with threads.
For example, I might have a win forms app which downloads a file. The app starts a worker thread to do the download (which prevents the GUI from locking up). The worker thread uses delegates to send status messages (eg download progress) back to the main program, so that the GUI can update the status bar.

- 931
- 1
- 8
- 17
The first line of usage is to replace the Observer/Observable (events) pattern. The second, a nice elegant version of the Strategy pattern. Various other usages can be gathered, though more esoteric than these first two I think.

- 51,312
- 7
- 89
- 111
Events, other anynch operations
Any time you want to encapsulate behavior, but invoke it in a uniform way. Event Handlers, call-back functions, etc. You can accomplish similar things using Interfaces and casts, but sometimes, behavior isn't necessarily tied to a type or object. Sometimes you just have behavior you need to encapsulate.

- 25,372
- 6
- 54
- 66
Lazy parameter initialization! Besides all previous answers (strategy pattern, observer pattern, etc), delegates allow you to handle lazy initialization of parameters. For example, suppose you have a function Download() which takes quite a lot of time and returns a certain DownloadedObject. This object is consumed by a Storage depending on a certain Conditions. Typically, you would:
storage.Store(conditions, Download(item))
However, with delegates (more precisely, lambdas) you can do the following, by changing the signature of store so that it receives a Condition and a Func<Item,DownloadedObject> and use it like this:
storage.Store(conditions, (item) => Download(item))
Therefore, storage will only evaluate the delegate if necessary, executing download depending on Conditions.

- 3,522
- 2
- 26
- 36
-
Minor point, but re "more precisely, lambdas" - you could do the same with an anonymous method in C# 2.0, although it would be more verbose: delegate (ItemType item) { [return] Download(item);} – Marc Gravell Oct 10 '08 at 13:21
-
Sure, same as LINQ: lambdas are nothing more than syntactic sugar for delegates. They just made delegates more accessible. – Santiago Palladino Oct 10 '08 at 13:27
-
Lambdas are slightly more than just delegates, as they're convertible to expression trees as well as delegates. – Jon Skeet Oct 10 '08 at 13:30
-
Well, lambdas can also be compiled to Expressions, which are *completely* different from delegates. But your example used Func<,>, which can be used from an anon-method. Expressions would be extremely painful to write in C# 2.0. – Marc Gravell Oct 10 '08 at 13:31
The comparison param in In Array.Sort(T[] array, Comparison comparison), List.Sort(Comparison comparison), etc

- 462
- 2
- 6
As far as I know, delegates can be converted to function pointers. This makes life MUCH easier when interoperating with native code that takes function pointers, as they can effectively be object-orientated, even though the original programmer didn't make any provision for that to happen.

- 144,682
- 38
- 256
- 465
Delegate's are used to call a method by it's reference. For example:
delegate void del_(int no1,int no2);
class Math
{
public static void add(int x,int y)
{
Console.WriteLine(x+y);
}
public static void sub(int x,int y)
{
Console.WriteLine(x-y);
}
}
class Program
{
static void Main(string[] args)
{
del_ d1 = new del_(Math.add);
d1(10, 20);
del_ d2 = new del_(Math.sub);
d2(20, 10);
Console.ReadKey();
}
}