Learn Use of Lambda Operator in C#

In C#, the lambda operator => is used in both lambda expressions and expression-bodied members.

1. Lambda Expressions

A lambda expression is a concise way to represent an anonymous method (a method without a name). It uses the lambda operator =>, which can be read as “goes to”. The left side of the operator specifies the input parameters (if any), and the right side holds the expression or statement block.

Here’s an example,

using System;
class Program
{
    static void Main()
    {
        Func<int, int> square = x => x * x;
        int number = 5;
        int result = square(number);
        Console.WriteLine($"The square of {number} is {result}");
    }
}

2. Expression-bodied members

Expression-bodied members are a syntactic shortcut for defining methods, properties, indexers, or event accessors using lambda syntax. They also use the lambda operator=>:

Expression-bodied Methods

public class MathOperations
{
    public int Add(int a, int b) => a + b;
    public int Multiply(int a, int b) => a * b;
}

In this example, Add and Multiply are expression-bodied methods. They take two integers as parameters and return the sum and product, respectively.

Expression-bodied Properties

public class Circle
{
    public double Radius { get; set; }
    public double Circumference => 2 * Math.PI * Radius;
    public double Area => Math.PI * Radius * Radius;
}

In this example, Circumference and Area are expression-bodied properties. They calculate the circumference and area of the circle, respectively.

Expression-bodied Indexers

public class SimpleIndexer
{
    private readonly int[] _array = new int[10];
    public int this[int i]
    {
        get => _array[i];
        set => _array[i] = value;
    }
}

In this example, the indexer is an expression-bodied member. It gets or sets the value of the element at the specified index.

Expression-bodied Constructors and Finalizers

public class Person
{
    private string _name;
    public Person(string name) => _name = name ?? throw new ArgumentNullException(nameof(name));
    ~Person() => Console.WriteLine($"Finalizing {_name}");
}

In this example, both the constructor and the finalizer are expression-bodied members. The constructor initializes _name and throws an exception if a name is null. The finalizer writes a message to the console when the object is being finalized.


Similar Articles