In C#, an anonymous method is a method that has no name and can be defined using the delegate
keyword. Anonymous methods enable you to write inline code blocks where delegates are expected. This can simplify your code by reducing the need for small, named methods that are only used in one place. Anonymous methods were introduced in C# 2.0, and they have been largely superseded by lambda expressions in later versions of C#.
Here's an example of an anonymous method in C#:
In this example, print
is a delegate of type PrintDelegate
that takes a string as a parameter. The delegate is assigned an anonymous method, which simply prints the passed string to the console.
Anonymous methods were a precursor to lambda expressions, which provide a more concise syntax and are more commonly used in modern C#. Here's how the same example would look using a lambda expression:
Both anonymous methods and lambda expressions have their usages, but lambda expressions are preferred for their concise syntax and capabilities. Would you like to dive deeper into delegates and lambda expressions or perhaps see more examples?