A delegate is an object that holds a reference to a method with a particular parameter list and return type.

It is basically like an object-oriented, type-safe function pointer.

Delegates basically make it possible to treat methods as entities. You can then assign a delegate to a variable or pass it as a parameter.

The classic delegate example uses events.

In C#:

HelloButton.Click += new EventHandler(HelloButton_Click);

Or the short-cut version of this code:

HelloButton.Click += HelloButton_Click;

This passes the HelloButton_Click method to a new EventHandler delegate.

In VB:

AddHandler HelloButton.Click, AddressOf HelloButton_Click

In VB, the AddressOf assigns the address of the HelloButton_Click method to the delegate.

Instead of using a named method for the delegate (in this example, a HelloButton_Click method), you can use a lambda expression.

In C#:

HelloButton.Click += (s, ev) =>
           MessageBox.Show("Hello World");

In VB:

AddHandler HelloButton.Click, Function(s, ev) _
           MessageBox.Show("Hello World")

In this case the lambda expression has two parameters: s (sender) and ev (eventArgs). When the Click event is generated on the HelloButton, the code displays the MessageBox.

You can use a lambda expression (inline function) anywhere a delegate is required. However, if the function requires more than a few lines of code, a named method is the preferred and recommended technique.

Enjoy!

Filed under: , , , , ,

Comments

# Lambda Expressions: An Introduction

Sunday, October 11, 2009 3:30 PM by Deborah's Developer MindScape

My presentation at our local Code Camp was fun. I covered a lot of material and had a GREAT audience

Leave a Comment

(required) 
(required) 
(optional)
(required)