Saturday, July 28, 2007

Simple Delegates

Over the past couple of days I have been learning the use of C# delegates. The simple explanation of a delegate is that it is a type that references a method. C++ developers know this as function pointers. The big difference between C++ function pointers and C# delegates is type safety. In practice a delegate looks like a cross between a method prototype and an object definition. In a way, it sort of is and this in part is what makes it so powerful. Also, a delegate can be reused for methods bearing the same method signature described by the delegate.

The most common use of delegates is for callbacks. I will cover callbacks in my next post as I am still doing a lot playing around with them before I write about how they work.

Here is a very simple example using a delegate:

class Program
{
delegate bool sentinel(int sent);

static void Main(string[] args)
{
int max = int.MaxValue;
int notMax = 1;

sentinel check = new sentinel(SampleMethod.isMaxInt);

Console.WriteLine(check(max));
Console.WriteLine(check(notMax));

}
}
class SampleMethod
{
public static bool isMaxInt(int testInt)
{
return (testInt == int.MaxValue) ? true : false;
}
}


References:

Delegates (C# Programming Guide)
http://msdn2.microsoft.com/en-US/library/ms173171(VS.80).aspx

Professional C# 3rd Edition
Robinson, Simon. Nagel, Christian. Glynn, Jay. Skinner, Morgan. Watson, Karli. Evjen, Bill. Wiley Publishing, Inc. 2004

No comments: