C# language: lambda expressions and anonymous methods

Today, quite a simple topic, we will start with lambda expressions, these are unnamed methods used together with delegates.

Lambda expressions

Example of lambda expression:

The general form of the lambda expression looks like this:

(parameters) => instruction block

You can leave the bracket when there is only one argument in the expression in our example, that is, x in the lambda expression corresponds to the parameter i in the delegate.

An example of lambda expression taking two parameters:

Lambda expressions are often used with Func and Action delegates:

The first two arguments of the Func delegate are the types of arguments given in the expression, and the third type means the type of returned result and our returned result in the expression is of course int because the type int times the type int gives int.

Lambda expressions without arguments look like this:

Anonymous methods

I do not know if you remember, but once we used the anonymous method in the lesson about events, the anonymous method is the method with the delegate word and no name and as you can also guess it uses delegates, let’s do one example with this method.

The same with the use of lambda expressions will look like this:

But you can also save it like this:


Certainly you used to be tempted at once to name a variable like her type, if you add a monkey character @ , you can do it, below is an example:

This content also you can find on my steemit blog: https://steemit.com/programming/@slawas/c-language-lambda-expressions-and-anonymous-methods

And on medium: https://medium.com/@sawomirkowalski/c-language-lambda-expressions-and-anonymous-methods-fb6e2241c8cd

If that post was useful for you share it with your friends :)

Post a comment

Notify about