Delegates

The capability to pass blocks of code around for use in another place is very powerful. A typical task that requires such a setting is the creation of a new background thread, which requires the code the thread should start executing. Some platforms have solved this by providing single-method interfaces like Runnable. This is quite some plumbing just to pass a piece of code around. Another possibility is the use of function pointers, but type safety suffers in such an approach.

Delegates combine the conciseness of function pointers while preserving the type safety characteristic of single-method interfaces but without the ceremony to deal with them. An example that deals with threading is shown here:

var t = new Thread(delegate(object ...

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.