Wednesday, May 19, 2010

Delegates

I thought I posted this a while back but it doesn't appear on my list of blogs so I'm reposting it.

A delegate is what used to be called a function pointer in C++. What it basically allows you to do is define the method signature of a function that is going to be called at run time without knowing what the function is at compile time.


Where this is useful is in cases where you have object(s) that need to register to be notified when something happens so it can take the proper action. This may sound a lot like an event; that's because an event is basically a variant of a delegate.

Two special types of delegates are the anonymous and multi-cast.

The anonymous is where you delcare a delegate but you define the function to be called inside the delegate declaration. Example: button1.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!"); };

So we're targeting a method that accepts object, EventArgs but we're actually defining the implemenation inside the declaration. So this delegate, when fired, would display Click! in a message box.
In the multi-cast delegate, you can target multiple method(s). But I don't recall ever using this feature so I don't have an example of it.

The most common place I use delegates is when I'm trying to filter a List of items. I normally use an anonymous delegate.

So assume I have a class, Employee with a FirstName field... and I've stored all my Employee records inside a List called MyList.

Example: List MyListOfBobs = MyList.FindAll(delegate(Employee e){return e.FirstName == "Bob";});

So here I would get back all the employees in MyList where the FirstName was equal to Bob.

I could also do something like this... MyList.FindAll(FindAllBobsMethod);

private static bool FindAllBobsMethod(Employee e)
{
if (e.FirstName == "Bob")
return true;
else
return false;
}

No comments:

Post a Comment