Lambda expressions1 min read

What are lambda expressions?

In short – lambda expressions are anonymous methods with:

  • No access modifier
  • No name
  • No return statement

We use them for convenience as we type less code for the same thing.

i.e.

Without lambda:

public string Greet(string name) {
return  $"I wish you a good day {name}";
}
static void Main(){
Console.WriteLine(Greet("Denis"));
}

With lambda:

static void Main() {
Func<string,string> Greet = name => name;
Console.WriteLine(Greet("Denis"));
}

As you can see, when using lambda expressions, we must use delegates (what are delegates).

When using collections we can see we get some default functions like “Find” which is accepts argument of type “Predicate”.

What is Predicate? It’s a delegate of type bool.

i.e.

 var toys = ToysRepo().GetToys();
var cheaperToys =  toys.FindAll( toy => toy.Price  <  10 ); // will return all toys whose price is less than 10 USD

As you can see in above example this is a pretty straight forward solution. The same thing could be achieved with writing additional bool function. This way we made our code simpler and more readable.

SUMMARY:

Lamda expressions are anonymous methods with:

  • No access modifier
  • No name
  • No return statement
(Visited 14 times, 1 visits today)

Leave a comment

Your email address will not be published. Required fields are marked *