Tuesday, 8 February 2011

CSharp: How to use delegates

Question:
Why should I use delegates?
How to use a delegate?



Answer:

In C# methods are not first order objects.
You cannot pass a method as an argument to another method, or store them in a list, or give it to someone to call your back.
So, if you want to pass a method around like an object you must create a delegate. That delegate encapsulates both an object instance and your method.

In C#, a delegate is a type that defines a method signature. For different method signatures you need different delegate types.

Event handlers are nothing more than methods that are invoked through delegates.



Here is an example
// the delegate takes one argument of type string and returns a string.
public delegate string ChangeString(string s);

public void RunSample()
{
    List<string> myList = new List<string> { "One", "Two", "Three" };

    DoForAll(myList, ToUpper);

    Console.WriteLine("----");

    DoForAll(myList, ToLower);

    Console.ReadLine();
}
// For all items in a list we want to do something (here we pass the method delegate
private void DoForAll(List<string> sList, ChangeString func)
{
    foreach (string s in sList)
    {
        Console.WriteLine( func(s) );
    }

}
private string ToUpper(string s)
{
    return s.ToUpperInvariant();
}
private string ToLower(string s)
{
    return s.ToLowerInvariant();
}
...

No comments: