Thursday, October 24, 2024

Static and Non-static lambda expressions in C# Explained


In C#, lambda expressions are a powerful feature that allows you to define inline, unnamed functions or delegates. A lambda expression is essentially a concise way to write an anonymous method in C#.
A static lambda expression is a lambda expression that does not capture any variables from its surrounding context. It only uses its input parameters and does not reference any local variables or instance members of the enclosing class.

Here's a general syntax for a static lambda expression in C#:

(parameters) => expression

- Parameters: The input parameters for the lambda expression, if any. These can be strongly typed or implicitly typed based on the context.
- Expression: The body of the lambda expression, which can be a single statement or a block of statements.

Example of a static lambda expression:

Look at the expression:

x => x * 2

In this example, the lambda expression takes a single parameter x and multiplies it by 2.

Static lambda expressions are often used in scenarios where you have a simple computation or transformation to perform and there's no need to capture variables from the surrounding scope. They are efficient and can be more readable and concise than defining a separate named method or using a traditional delegate.

Non-Static Lambda Expression Example

In C#, lambda expressions can be both static and non-static. Non-static lambda expressions capture variables from the surrounding context, making them powerful for capturing state and behavior. Here's an example of a non-static lambda expression:
using System;

class Program
{
    static void Main(string[] args)
    {
        int num = 10;

        // Non-static lambda expression capturing a variable from the surrounding context
        Func<int, int> incrementNum = (x) => x + num;

        int result = incrementNum(5);  // Calling the lambda expression

        Console.WriteLine("Result of incrementNum(5): " + result);
    }
}
In this example, the lambda expression (x) => x + num is non-static and captures the num variable from the surrounding context. The lambda expression adds the argument x to the captured variable num. When you call incrementNum(5), it adds 5 to the captured value of num (which is 10) and returns 15.

No comments:

Post a Comment

Hot Topics