What are Anonymous methods and Lambda Expressions in C#?

  • An Anonymous function is an inline block of statements which can be used wherever a delegate type is expected.
  • Anonymous functions can be created by using an anonymous method or a lambda expression.
  • An Anonymous method is a method definition which doesn't contain a method name, that can be assigned to a delegate type. These were introduced in C# 2.0. It is created by using a delegate operator, which can be converted to a delegate type.
  • A Lambda Expression is a simpler and more expressive way of defining functionality which were introduced in C# 3.0. It is a set of arguments with the body which are separated by a lambda declaration operator (=>)
delegate void Del(string str);

// declaring an anonymous method
// assigning to a Delegate type Del
Del d1 = delegate (string str)
{
    Console.WriteLine($"Hello {str}");
};

// declaring a lambda expression
// assigning to a Delegate type Del
Del d2 = str =>
{
    Console.WriteLine($"Hello there! {str} via a Lambda Expression.");
};
  • An Anonymous function is an inline block of statements which can be used wherever a delegate type is expected.
  • Anonymous functions can be created by using an anonymous method or a lambda expression.
  • An Anonymous method is a method definition which doesn’t contain a method name, that can be assigned to a delegate type. These were introduced in C# 2.0. It is created by using a delegate operator, which can be converted to a delegate type.
  • A Lambda Expression is a simpler and more expressive way of defining functionality which were introduced in C# 3.0. It is a set of arguments with the body which are separated by a lambda declaration operator (=>)
delegate void Del(string str);

// declaring an anonymous method
// assigning to a Delegate type Del
Del d1 = delegate (string str)
{
    Console.WriteLine($"Hello {str}");
};

// declaring a lambda expression
// assigning to a Delegate type Del
Del d2 = str =>
{
    Console.WriteLine($"Hello there! {str} via a Lambda Expression.");
};

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *