delegates, anonymous methods & lamda expressions


In this article, we will discuss about the basic concept of the delegates, anonymous methods and lamda expressions. We will use one single code example of a add method, which takes two input parameters and return their sum. So we have a simple function with the code as:

public static Int32 Add(Int32 a, Int32 b)
{
return a + b;
}

Delegate: Same definition you might have seen on the other sources, a delegate acts as a function pointer and can be used to execute a function, by simply passing its name(to register that method) and then invoke it, by calling the delegate instance. But the condition is that the signature of the delegate must be same as that of the function that we need to call through this delegate.
So now we will use a delegate to call the above method. For this, we need to first create a delegate.

public delegate Int32 Calculate(Int32 a, Int32 b);
Calculate _calculate = new Calculate(Add);
Console.Write("Sum of numbers using Delegate : " + _calculate(21, 22));

Anonymous methods: Anonymous methods were introduced in C# 2.0, as a shorter syntax for passing the function definition directly to the delegate parameter, instead of creating a method and passing its name explicitly to it. We can simply pass the logic of our function inside the delegate call, instead of creating a function for it.
So now we will convert the above code to calculate the sum using anonymous method.

Calculate _calculate = delegate(Int32 a, Int32 b)
{
return a + b;
};
Console.Write("Sum of numbers using Anonymous method : " + _calculate(50, 50));

As we can see above, we replaced the original function name with the actual function logic, in the delegate initialization. Run the code and see the results.

Lamda expressions:
Finally we have the concept of lamda expressions. Introduced in C# 3.5, they further shorten the syntax of creating anonymous methods. It uses the => or lamda operator, to declare the anonymous methods. Let’s convert our code to use the lamda expression.

Calculate _calculate2 = (a, b) => a + b;
Console.Write("Sum of numbers using Lamda expressions : " + _calculate2(10, 10));

To specify any input parameters, we set them on the left of the => operator, in the brackets, as we did above (a, b) . If we do not have any input parameter, we can simply use empty brackets as (). On the other hand, the statements on the right side of the => operator are called as Expression lamda. If we need to have multiple statements in the expression lamda, we need to use the {} brackets to enclose them and are called Statement lamda (Source MSDN)

The procedure to call the delegate remains the same. What changes is, how we use the actual function with the delegate created for it. The complete code is listed below:

delegates, anonymous methods & lamda expressions

Lamda expressions in LINQ query: lamda expressions are used extensively in the linq queries. You must have written the queries like below:

List<Int32> _lst = new List<Int32>();
_lst.Where(x => x > 10).ToList();

Let’s try to see why we can use the lamda expressions here. See the code below:

delegates, anonymous methods & lamda expressions

As we can see, it expects a Func<int, bool> delegate, which takes an input parameter and returns a boolean value. Since we can directly provide lamda expression based definition to the delegate, like we did above in our Calculate example, we can directly write the lamda expressions with these methods. In-fact we can write the anonymous method directly in this method or could have declared the Func delegate explicitly, with anonymous method syntax and then passed it to this method. So we can have the code as:

delegates, anonymous methods & lamda expressions

So this was about the basic concept of delegates, anonymous methods and lamda expressions. Hope you enjoyed reading it…!!!

Advertisements

About Jasminder

.Net developer and blogger by profession, keen to learn new technologies, love nature, music and cricket.
This entry was posted in C#, Linq and tagged . Bookmark the permalink.

I have a suggestion..

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s