When would you use delegates in C#? [closed]
What are your usage of delegates in C#?
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)
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");
}
}
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.
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!