Sunday, April 28, 2024 19:26

Table of contents >> Delegates, Lambda Expressions, Events > Anonymous methods

Anonymous methods

Remember from the lesson lambda expressions that we can declare a method locally, without a name, and use it only in one place, where we declare it. This is an example of a lambda expression:

Short revision: I declared a delegate named SomeDelegate that accepts any method that takes an int as parameter and returns a bool, then I assigned this expression to it: i => i > 5, which is the actual lambda expression, and the compiler is perfectly happy, because it can infer the fact that i is an int, and, yes, i > 5 is an expression that returns a boolean value.

Lambda expressions were introduced in C# 3.0, while anonymous methods were added in version 2.0 of C#. For this reason alone, think of lambda expressions as being a nicer form of anonymous methods, or think of them as anonymous methods, but better, improved.

For declaring an anonymous method, we have the following syntax:

The above code is similar to the lambda expression one, it does the same thing. Only, in this case we are forced to use the keyword delegate, then specify the i parameter between parenthesis, and also state that it is an int, then use curly brackets, and all of a sudden we have an actual method body, inside which we are also forced to use the return keyword, and so on. All in all, it is exactly like a real method, except we don’t use access modifiers, return types or method names.

Just like lambda expressions, we are allowed to have more than one statement or expression inside the method’s body, but I personally believe that if you have a method body that has more logic than a simple expression, it is probably a strong indicator that you should declare a separate, normal method.

As a conclusion, don’t use anonymous methods anymore, use lambda expressions, they are newer, shorter and easier to use.

Tags: , , ,

Leave a Reply



Follow the white rabbit