Tag Archives: lambda

Lambda Expressions

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:

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:

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:

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.

Filled under C#. No Comments.