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.");
};
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.

Privacy Overview
Referbruv

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.