Tuesday, March 10, 2009

C# Delegates

I posted about C++'s function pointers a few posts back. They're pretty nifty, even though my experience with them is pretty limited. I recently learned about something called delegates in C#. They're sort of like C++'s function pointers, but more "safe". They allow you to (like C++'s function pointers) to pass a method to another method for later execution.

It pretty much works like this: You first declare your delegate for use. How you declare it depends on the type of methods you want it to be able to handle. If you wanted it to handle methods with the return type of void and that take one int, you would do this:

public delegate void MyDel(int val);

This creates a delegate that accepts methods of that same signature. After this, you're going to need a method declared somewhere that meets these parameters for it to use. Here's a short example:

public static void DelMethod(int i)
{
System.Console.WriteLine(i);
}

To use your delegate, you first have to assign the method you want it to hold, then call it somewhere.

MyDel handler = DelMethod;
handler(42);

The above code creates a custom delegate using the signature we declared above and sets it equal to the method we created. Then the next line uses the delegate to run the method stored in it and passes the number 42. The output to a console app would just be "42".

Another nice thing about delegates is that they can be added together. If I have three delegates (two with methods stored in them and one new one), I could set the third one equal to the first two added together and when I used the third delegate, it would execute both methods now stored in that delegate in the order they were stored in it.

I'm just starting to learn about this subject, but so far C++'s function pointers make more sense to me. I didn't have to scratch my head as much when learning them. That's not to say delegates aren't useful...they definitely are. It's just taking me longer to understand them fully than it did to learn C++'s function pointers. There are definitely many uses for delegates, but that'll have to be for another post. I just wanted to post about this while it was still fresh in my mind.