Search code examples
c#lambdadelegatesconsole-applicationanonymous-methods

Write anonymous expression as lambda expression


How to write the same 'Anonymous Expression' in 'Lambda Expression.'

namespace AnonymouseAndLambdaExpression
{
    // Delegate
    public delegate bool NumberHandler(int number);

    class Program
    {
        static void Main(string[] args)
        {
            //..
            NumberHandler _NumberHandler = delegate (int Number) { return Number == 100; };

            bool result = _NumberHandler(100);
            Console.WriteLine("Result : {0}" , result);
        }
    }
}

Help will be appreciated.


Solution

  • because NumberHandler takes one parameter of type int and returns a bool it would just be:

    NumberHandler _numberHandler = (int number) => number == 100;
    

    or:

    NumberHandler _numberHandler = number => number == 100;
    

    Further, I'd avoid reinventing the wheel and instead use Predicate<int> i.e.

    Predicate<int> _numberHandler = number => number == 100;
    

    I'd also highly suggest you take a read on Lambda Expressions (C# Programming Guide)