This is a mirror of official site: http://jasper-net.blogspot.com/

Back to Basics: Delegates, Anonymous Methods and Lambda Expressions

| Monday, May 2, 2011
Introduction

Like generics, delegates are one of those features that developers use without really understanding. Initially this wasn’t really a problem since delegates were reserved for fairly specific purposes: implementing callbacks and as the building-block for events (amongst a few other edge cases). However, each version of .NET has seen delegates evolve, first with the introduction of anonymous methods in 2.0 and now with lambda expressions in C# 3.0. With each evolution, delegates have become less of an specific pattern and more of a general purpose tool. In fact, most libraries written specifically for .NET 3.5 are likely to make heavy use of lambda expressions. As always, our concern isn’t just about understanding the code that we use, but also about enriching our own toolset. Seven years ago it wouldn’t have been abnormal to see even a complex system make little (or no) us of delegates (except for using the events of built-in controls). Today, however, even the simplest systems heavily relies on them.

Delegates

The best way to learn about all three framework/language feature is to start from the original and build our way up, seeing what each evolution adds. Delegates have always been pretty simple to understand, but without any good reason to use them, people never really latched on to the concept. It’s always easier to understand something when you can see what problem it solves and how it’s used – and examples of delegates always seem contrived.

Delegates are .NETs version of function pointers – with added type safety. If you aren’t familiar with C or C++ (or another lower level languages) that might not be very helpful. Essentially they let you pass a method into another method as an argument. Although many developers understand the concept in languages such as JavaScript, the strictness of C#/VB.NET makes it a little more confusion. For example, the following JavaScript code is completely valid (and even common):

function executor(functionToExecute)
{
   functionToExecute(9000);
}
var doSomething = function(count){alert(“It’s Over ” + count);}
executor(doSomething);

Read more: CodeBetter

Posted via email from Jasper-net

0 comments: