C# - Dynamic Behavior with Lambda Expressions and Delegates
Keyur Ramoliya
Posted on October 15, 2023
Lambda expressions in C# allow you to define anonymous methods or functions on the fly. Combined with delegates, you can create dynamic behaviors in your code, where you determine what a method does at runtime.
Here's an example that demonstrates this concept:
using System;
public class Program
{
public static void Main()
{
// Define a dynamic behavior using a lambda expression
Func<int, int, int> dynamicOperation = (x, y) => x + y;
// Use the dynamic behavior to perform an operation
int result = PerformOperation(5, 3, dynamicOperation);
Console.WriteLine($"Result: {result}");
}
public static int PerformOperation(int a, int b, Func<int, int, int> operation)
{
return operation(a, b);
}
}
In this example, we define a dynamicOperation
variable as a Func<int, int, int>
delegate that takes two integers and returns their sum. We can change the behavior of dynamicOperation
by assigning different lambda expressions to it at runtime.
The PerformOperation
method accepts two integers and a delegate representing an operation to perform. In this way, you can pass different operations to PerformOperation
and achieve dynamic behavior based on the operation you provide.
This approach is highly flexible and allows you to create code that adapts to changing requirements by changing the behavior of the delegates at runtime. It's a powerful technique for building extensible and configurable components in your applications.
Posted on October 15, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.