Denis Jakus

making tech less cryptic

CTO x Unique People

CTO Note

Lambda expressions1 min read

29 October 2017 .NET

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
Taggs:
Related Posts
How to organize Visual Studio projects

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like In my latest Youtube video,…

Caching in DotNet Core WebAPI using Strategy Pattern

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like Let me write today about…

Write a comment
Exit mobile version