Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

October 11, 2009

Delegates

Filed under: C#,Lambda Expressions,VB.NET @ 3:29 pm

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!

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs