In C# 2.0 there are anonymous methods, which allows you to write your method code inline instead of creating a new method in your class. In C# 3.0 there is a new feature – lambda expressions. The goal of this expressions is the same as the anonymous methods, but the syntax is more concise.
Let’s have the following code:
1 2 3 4 5 6 7 8 9 10 11 12 |
class LambdaExpressionTest { public delegate int myDelegate(int x); static void Main() { myDelegate testFunc = new myDelegate(LambdaExpressionTest.myFucn); Console.WriteLine(testFunc(5)); // returns 23 } public static int myFucn(int x) { return x * x - 2; } } |
If we want to rewrite this code using anonymous method, it will get the following look:
1 2 3 4 5 6 7 8 9 10 |
class LambdaExpressionTest { public delegate int myDelegate(int x); static void Main() { myDelegate testFunc = new myDelegate(delegate(int x) { return x * x - 2; }); Console.WriteLine(testFunc(5)); } } |
And if we want to rewrite this code using lambda expressions, it will look like this:
1 2 3 4 5 6 7 8 9 10 |
class LambdaExpressionTest { public delegate int myDelegate(int x); static void Main() { myDelegate testFunc = x => x * x - 2; Console.WriteLine(testFunc(5)); } } |
Isn’t it so simple? 🙂 The sign ‘=>‘ is read as “goes to”. We first indicate the arguments of our method and after that we do our calculations in it.