In this tutorial, you will explore the variance between a lambda expression and a delegate in C#. Prior to delving into their distinctions, it's essential to grasp the concepts of lambda expressions and delegates along with their syntax and illustrative examples.
What is the Delegate?
A delegate in C# is a reference type that represents a method with a specific signature. Delegates enable indirect method invocation and essentially serve as a pointer to a function.
Delegates allow functions to be stored in data structures, returned from functions, and passed as arguments.
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's consider an example to demonstrate the use of delegates 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 named MathOperationsDelegate is defined in this C# code to represent functions that take two double inputs and produce a double output. Within the Demo class, two static functions, namely Addition and Subtraction, are implemented to perform addition and subtraction operations correspondingly. These functions are linked to delegate objects established within the Main Method. Upon invoking these delegate objects with values 10 and 20, the associated functions execute. Subsequently, the console showcases the outcomes of both addition and subtraction computations. This script illustrates the usage of delegates to introduce flexibility in method executions by introducing an intermediary layer for function calls.
What is the Lambda Expression?
In C#, lambda expressions offer a straightforward syntax for creating anonymous functions or methods. They act as convenient ways to define expressions or delegates that can be stored in variables or used as arguments in method calls.
Syntax:
It has the following syntax:
(parameters) => expression
Parameters: In lambda expressions, parameters are represented by parentheses . They serve as placeholders for the input values. When there are no arguments, empty parentheses should be used.
The lambda operator, also known as the "goes to" operator, divides the lambda expression's body from its parameters using a combination of the equal sign '=' and the greater-than symbol '>'.
Expression: Any expression contained within curly braces {} can be defined following the lambda operator.
In case the lambda expression consists of a single expression, it can be directly placed after the lambda operator.
The use of curly braces {} is essential for enclosing any statements needed by the lambda expression.
Example:
Let's consider a scenario to demonstrate 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 concise and clear manner in which lambda expressions facilitate the creation of inline functions enhances the clarity and sustainability of C# code. They showcase the versatility of lambda expressions in addressing various scenarios and performing diverse operations.
Difference between a lambda expression and a delegate in C#
In C# programming, both lambda expressions and delegates play essential roles. Delegates provide a means to encapsulate method references, callback mechanisms, and event-driven programming, while lambda expressions offer a more concise and expressive method 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. |