- C# Lambda Introduction
- C# Lambda Part 2
- C# Lambda Part 3
A Lambda expression is nothing more than an anonymous method. It has no access modifier (public/private), it has no name, and it has no return statement. Why do we use them? For convenience. We can write less code and achieve the same thing. Also, the code is more readable. We have part two of this post called C# Lambda Part 2.
We have a post called C# Introduction.
We can look at Lambda expressions with an example. First we go back an look at delegates.
using System; namespace LambdaExpressions { class Program { static void Main(string[] args) { Console.WriteLine(Square(5)); } static int Square (int number) { return number * number; } } }
If we try to just create a Lambda expression it doesn’t work, as you can see in the screenshot of Visual Studio below.
Let’s create a delegate called squareDel. The code below works fine. squareDel is just a pointer to a function. So we can use squareDel just as though we were using Square.
static void Main(string[] args) { // use a delegate (squareDel) to point to our Square function // Func<argumrnt type, return type> Func<int, int> squareDel = Square; Console.WriteLine(squareDel(3)); Console.ReadKey(); } public static int Square(int number) { return number * number; }
Now we introduce the use of Lambda expressions. When we see => we read that as “goes to“.
Here is our Example
static void Main(string[] args) { Func<int, int> squareDel = m => m * m; Console.WriteLine(squareDel(4)); Console.ReadKey(); }
We don’t need to write the function Square shown above if we use a Lambda expression instead. In the next example we want to multiply a number by a factor, such as 5 in this case.
static void Main(string[] args) { const int factor = 5; // factor is not out of scope! Func<int, int> multiplier = n => n * factor; var result = multiplier(10); Console.WriteLine(multiplier(6)); Console.WriteLine(result); }
So the form of the Lambda expression is m => n, where m is the INPUT and n is the OUTPUT, so Lambda is INPUT => OUTPUT.
Consider the code below. Our new delegate takes three numbers in and sends one number out. We have to be sure we define Func<> properly.
static void Main(string[] args) { Func<int, int, int, int> multDel = (m,n,o) => m*n*o; Console.WriteLine(multDel(4,3,7)); Console.ReadKey(); }
So what about this below? We are getting a little worried that we might get an overflow of the integer returned, so we’ll return a long.
Func<int, int, int, long> multDel = (m,n,o) => m*n*o;
Predicate
Before moving on to the next post, we need to ask: “What is a predicate?” In a SQL Server post called SQL Server Like Predicate The term “predicate” is used to refer to an expression that determines whether something is true or false. Or in other words, it makes an assertion and returns true or false based on that.