Friday, 13 February 2009

Anonymous methods & Lambda expressions

When we declare a Delegate we usually write this code,

public delegate string aDelagateFunc(string name);

Now create a function with same signature
string otherfunc(string n)
{
return "hello " + n;
}

call this function through delegate

aDelagateFunc del = new aDelagateFunc(otherfunc);
stringstrreturnval = del("World");

MessageBox.Show(strreturnval);


To reduce this amount of code , to make the called function as Inline function , C# 2.0 introduced new feature with called " anonymous Methods".

Lets declare another delegate
public string string aDelagateFunc2(string name);

associate delegate with anonymous method
aDelagateFunc2 del2 = delegate(string s) { return "hello " + s; };
Now call anonymous method
MessageBox.Show(del2("anonymous method"));

In C# latest version ( with .Net 3.0 installed) same amount of code can be done even more shorter as anonymous methods which is called lambda expression.

in Lambda expression => operator is used to indicate the parameters on left side as input parameters(similiar to a function input parameters) and right side contain statement block(function body).

let define another delegate
public delegate string LambdaDelegate(string name);

on a button click event , write this code

LambdaDelegate _lamdadel = strname => "hello " + strname;

string strResult = _lamdadel("Lamda Expression Example");
MessageBox.Show(strResult);

As we see here , lambda expression code makes coding styles even more simplier.

strname as input parameters is not given explicit type,it is implicitly converted to type string by complilor , however type can be defined explicitly as

LambdaDelegate _lamdadel = ( string strname) => "hello " + strname;

It is called Type Inference as C# compiler infer the type of input parameters from function body( determine how paarmeters are used in function body.)



There can be more than one input parameters seperated by commas.
LambdaDelegate _lamdadel = ( string strname,string strlastname) => "hello " + strname;
It is not necessary to always providea input parameters , you can leave it black if no input parametrs are required like LambdaDelegate _lamdadel= ()=>"hello ";

Query operators for example count can also be used with lambda expression.

int[] numb=new int[]{1,2,3,4,5,6,7,8,9};
int _inttotal = numb.Count(n => n % 2 != 0);
MessageBox.Show(_inttotal.ToString());


This lambda expression is used in LINQ as in given sample Zenab's Tech Blog.Net: LINQ Basics

Next topic will be on ADO.net Entity framework MODEL and LINQ to SQL.

2 comments:

  1. is this article complete?

    ReplyDelete
  2. Thanks, i got the point.

    ReplyDelete