C# Lambda Expressions

C# Code Snippets Func Action Lambda


In this code snippet, we will take a look at lambda expressions, Func<T> and Action<T> in C#.

Func<T> is simply a more compact way of defining a delegate/function pointer while Action<T> is the exact same thing as Func<T> but for methods that return void. 

The lambda operator () => is a more compact way to define an anonymous method that can then be assigned to a delegate or passed into another method as a parameter. It’s very often combined with LINQ to form very concise queries that all fit into a single line of code.

Let’s have a look at the code below to see how to use lambda expressions, Func<T> and Action<T>.


//Func<> is simply a more compact way of defining a delegate/function pointer. 
//Func<return type, input param1, input param2, ...> 
Func<double, double, double> operation = addition;
Calculate(operation, 10, 5);

//Action<> is the same as Func<> but is meant for methods that return void.
//Action<input param1, input param2, ...> 
Action<int, int> myAction = MyTestVoidMethod;

//The lambda operator () => is simply a more compact way of defining an anonymous method.
//It can be used in conjunction or as a more compact replacement for Action<> and Func<>.
Func<double, double, double> add = (a, b) => { return a + b; };
Calculate(add, 8, 8);

//Or an even more compact way.
Func<double, double, double> sub = (a, b) => a - b;
Calculate(sub, 8, 8);

//Or even more compact without Func<> or Action<>.
Calculate((a, b) => a * b, 8, 8);


static void MyTestVoidMethod(int input, int input2) 
    Console.WriteLine($"Doing something with {input} and {input2}.");

static void Calculate(Func<double, double, double> operation, double operand1, double operand2) 
    double result = operation(operand1, operand2);


static double addition(double a, double b)
    return a + b;

static double subtract(double a, double b)
    return a - b;

static double multiply(double a, double b)
    return a * b;

static double divide(double a, double b)
    return a / b;

Resulting output:


Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger