In this article, you will learn about the difference between a lambda expression and a delegate in C#. But before discussing their differences, you must know about the lambda expression and a delegate with their syntax and examples.
What is the Delegate?
A reference type representing a method with a particular signature in C# is called a delegate . It allows indirect method invocation and acts essentially as a reference to a function.
Delegates enable methods to be stored in data structures, returned from methods, and passed as parameters.
Syntax:
It has the following syntax:
delegate return_type DelegateName(parameter_list);
Parameters:
- return_type: It represents the return types of the delegate's methods. It specifies the type of data that the Method will return upon execution. If the Method doesn't return anything, void is used.
- DelegateName: It is a name used to refer to the defined delegate type. It is utilized to instantiate delegate instances.
- parameter_list: The list of parameters that the delegate's referenced methods will take is defined here. If there is more than one parameter, the parameters are separated by commas and consist of a type and a name.
Example:
Let us take an example to illustrate the delegate in C#.
using System;
// Declaring a delegate type named MathOperationDelegate
delegate double MathOperationsDelegate(double p, double q);
class Demo
{
//Method to Addition of two numbers
static double Addition(double j, double k)
{
return j + k;
}
//Method to Subtraction of two numbers
static double Subtraction(double j, double k)
{
return j - k;
}
static void Main(string[] args)
{
MathOperationsDelegate addDelegate = new MathOperationsDelegate(Addition); MathOperationsDelegate subtractDelegate = new MathOperationsDelegate(Subtraction);
double ans_Add = addDelegate(10, 20);
double ans_Subtract = subtractDelegate(10, 20);
Console.WriteLine("The result of the Addition of two numbers: " + ans_Add);
Console.WriteLine("The result of the Subtraction of two numbers: " + ans_Subtract);
}
}
Output:
The result of the Addition of two numbers: 30
The result of the Subtraction of two numbers: -10
Explanation:
A delegate called MathOperationsDelegate represents the methods in this C #code that accept two double parameters and return a double result. The Demo class declares two static methods, Addition and Subtraction that carry out addition and subtraction operations, respectively. Addition and Subtraction are assigned to delegate instances created in the Main Method. The associated methods are then called after these delegate instances are called with parameters 10 and 20. Lastly, the console displays the results of the addition and subtraction operations. This code demonstrates how to use delegates to allow dynamic behaviour in method calls by providing a level of indirection for method invocation.
What is the Lambda Expression?
In C#, lambda expressions provide a simple syntax for composing anonymous functions or methods. They are shortcuts for defining expressions or delegates that may be assigned to variables or passed as arguments to methods.
Syntax:
It has the following syntax:
(parameters) => expression
Parameters: The parameters are denoted by parenthesis . For the lambda expression, they stand in for the input parameters. Need to use empty brackets if there are no arguments.
Lambda Operator (=>): The lambda operator, sometimes referred to as the "goes to" operator, separates the lambda expression's body into its parameters. It comprises the equals sign '=' and the greater-than symbol '>' .
Expression: Any expression enclosed in curly braces {} can be specified after the lambda operator.
- If the lambda expression comprises just one expression, the expression can be specified immediately following the lambda operator.
- Curly braces {} are used to enclose any statements required by the lambda expression.
Example:
Let us take an example to illustrate the Lambda Expression in C#.
using System;
class Demo
{
static void Main(string[] args)
{
//Lambda expression with just one parameter
Func<int, int> square = s => s * s;
Console.WriteLine("The square of 10 is: " + square(10));
// Lambda expression with multiple parameters
Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine("The sum of the 26 and 18 is: " + add(26, 18));
// Lambda expression with no parameters
Action greet = () => Console.WriteLine("Lambda Expression!");
greet();
// Lambda expression with expression body
Func<int, string> checkSign = q => q > 0 ? "Positive" : "Non-positive";
Console.WriteLine("The sign of -15 is: " + checkSign(-15));
// Lambda expression with statement block
Func<int, int, int> multiplyAndAdd = (j, k) =>
{
int ans = j * k;
return ans + 19;
};
Console.WriteLine("The result of (14 * 18) + 19 is: " + multiplyAndAdd(14, 18));
}
}
Output:
The square of 10 is: 100
The sum of the 26 and 18 is: 44
Lambda Expression!
The sign of -15 is: Non-positive.
The result of (14 * 18) + 19 is: 271
Explanation:
The short and expressive way these lambda expressions enable the definition of inline functions improves the readability and maintainability of C# code. They demonstrate how lambda expressions may be flexibly used to handle different situations and types of operations.
Difference between a lambda expression and a delegate in C#
In C# programming, both lambda expressions and delegates are necessary. While delegates offer a mechanism for encapsulating method references, callback mechanisms, and event-driven programming, lambda expressions offer a clearer and more expressive way to define inline functions.
| Feature | Lambda expression | Delegate |
|---|---|---|
| Definition | The => operator is used to define anonymous inline functions. | A type that represents references to methods with a specific signature. |
| Parameters | It can capture variables from the enclosing scope (closures). | The delegate declaration contains specific definitions for parameters. |
| Type Inference | Automatically inferred by the compiler from the context in which they are used. | It is necessary to define the delegate type explicitly. |
| Invocation | It is typically utilised to create delegate objects without explicitly defining methods. | It requires passing the method reference to the delegate and creating an instance. |
| Usability | LINQ queries, functional programming patterns, and event handling are common uses. | Fundamental building blocks for event-driven programming and defining callback mechanisms. |