From Delegates to Lambda Expressions

Delegates:

Delegate was a wonderful addition to .NET 1.1 in early 2000. It is a type that can store a pointer to a function. The below snippet shows the way we would use delegates in our everyday programming.
Listing 1.1

delegate DataTable GetUserDetailsDelegate(int userID);

class Program
{
static void Main(string[] args)
{
GetUserDetailsDelegate GetUserDetails = new GetUserDetailsDelegate(GetUserDetailsByUserID);
DataTable dt = GetUserDetails(1);
}

private DataTable GetUserDetailsByUserID(int userID)
{
return new DataTable();
}
}

Anonymous Methods

C#2.0 was improved to allow working with delegates through anonymous methods. I said C#, because VB.NET doesn’t offer support for anonymous methods. These anonymous methods allow us to write shorter code and avoid the need for explicitly named methods. Let's modify the code in Listing1.1 and re-write it using anonymous methods.
Listing 1.2
delegate DataTable GetUserDetailsDelegate(int userID);

class Program
{
static void Main(string[] args)
{
GetUserDetailsDelegate GetUserDetails = delegate(int userID) { return new DataTable(); };
var dt = GetUserDetails(1);
}

Lambda Expressions

Now, Starting with C# 3.0, instead of anonymous methods we can use lambda expressions.
Listing 1.3
C#
var GetUserDetails = userID => { return new DataTable(); };
var dt = GetUserDetails(1);
VB.NET
Dim GetUserDetails = Function(x) New DataTable()
Dim dt = GetUserDetails(1)

The anonymous method introduced in C#2.0 is verbose and imperative in nature. In contrast, lambda expressions provide a more concise syntax, providing much of the expressive power of functional programming languages. It is a superset of anonymous methods with additional functionalities like inferring types, using both statement blocks and expression as bodies etc.

Note that, In the above lambda expression left hand side variable is of anonymous type. Anonymous type is a new language enhancement that enable us to declare types without names. If you are concerned about their limitations and don't want to use them then you can use Func<T, TResult> generic delegate in lieu of anonymous types.

Listing 1.4
C#
Func<int,DataTable> GetUserDetails = userID => { return new DataTable(); };
var dt = GetUserDetails(1);
VB.NET

Dim GetUserDetails As Func(Of Integer, DataTable) = Function(x) New DataTable
Dim dt = GetUserDetails(1)



HTH,

0 comments:

Post a Comment