Exploring lambda expression in C#

Lambda expression is an anonymous function and inline delegate which lets you to create local function to pass arguments or return type as a value of the function. Although anonymous methods helps you to create inline method but anonymous methods force you to define the parameter and return types:

  1.         delegate void NumberChanger(int n);
  2.         NumberChanger _numberChanger = delegate(int x)
  3.         {
  4.             Console.WriteLine("");
  5.         };

But a lambda expression is  a method without a declaration, access modifier, return value, and even any name:

  1.    delegate void NumberChanger(int n);
  2.    NumberChanger _numberChanger = x => Console.WriteLine("Anonymous Method: {0}", x);

Another example:

  1.             int[] a = { 2, 3, 4, 5, 6, 7, 8, 9 };
  2.             Func<int, bool> func = delegate(int l)       //func via delegate declaration
  3.             {
  4.                  return l == 2;
  5.             };
  6.             Func<int, bool> func = l => l == 2;          //func via lamda expression

lambda expression is more fluent and easier and most convenient way to create delegate. Note that Lambda expression has no meaning outside the context of the .NET. The lambda expression syntax uses the => operator: "Parameters => Executed code" for example : x => x * x  specifies a parameter with name x and returns the value of x squared. when you create a lambda, for example:

  1.             int[] a = { 2, 3, 4, 5, 6, 7, 8, 9, 9 };
  2.             int b = a.Count(n => n % 2 == 1);

It's actually a method with one parameter:

  1.           int b = a.Count((n) => n % 2 == 1);

Parentheses are not required when the lambda has one input parameter, but if you have more than one input parameter you should put parentheses just like method definition:

  1.             int d = a.First(i => ((i & 1) == 1));

Or if you have a delegate defined like this:

  1.    delegate long X(int x, int y, int z);

 Your lambda  should be like this:

  1.   X lambda= (x, y, z) => x * y * z

as you don't need to specify the name of the function and return type or and access modifier in lambda expression, so you don't need to look elsewhere for the method's definition when you reading your codes. But notice that Lambda expressions should be short because A complex definition makes the calling code difficult to read, maybe more difficult than writing anonymous methods! Cheers


Tags: C#


comments powered by Disqus