C#11-And , Or Operators in lambda Expressions

we can use the new and and or operators in C# 11 to create enhanced lambda expressions as follows

using System;

class Program
{
    static void Main(string[] args)
    {
        Func<int, bool> isEven = x => x % 2 == 0;
        Func<int, bool> isPositive = x => x > 0;

        // Using the 'and' operator
        Func<int, bool> isEvenAndPositive = isEven and isPositive;
        Console.WriteLine(isEvenAndPositive(4)); // Output: True
        Console.WriteLine(isEvenAndPositive(-4)); // Output: False

        // Using the 'or' operator
        Func<int, bool> isEvenOrPositive = isEven or isPositive;
        Console.WriteLine(isEvenOrPositive(4)); // Output: True
        Console.WriteLine(isEvenOrPositive(-4)); // Output: True
    }
}

Leave a Reply