2009년 10월 23일 금요일

Lamda Expression in C#

Lamda expression is an anonymous function that can contain expression and statement. Lamda expression can be used to create deletegates and tree types.

Lamda Operator

 "=>" : read as 'goes to'
" e.g. x => x * x " , which is read as x goes to x times x.


Lamda Expression
An expression lamda basic form:
" (input parameters) =>  expression "

If the lamda has one parameter, the parenthese is optional; Otherwise, If parameters are more than two, the parenthese is required.
" (x, y) => x == y "

The compliler sometimes doesn't understand input types. When this occur, specify the types explictly.
" (int x, string s) => s.Length > x "


Statement Lamda
basic form:

" (input parameters) => {statement;} "


The body of a statement lambda can consist of any number of statements; however, in practice there are typically no more than two or three.


Three examples are expression comparison between delegate and lamda. The first is an example for delegate and other thngs for lamda.

Example 1 ( deleage )
public delegate void IntDelegate(int a,int b);
static void Main(string[] args)
{
   IntDelegate d;
   d = ADD;
   d += SUB;
   d(10, 20);
}
public static void ADD(int a, int b)
{
   Console.WriteLine("ADD = {0}", a+b);
}
public static void SUB(int a, int b)
{
   Console.WriteLine("SUB = {0}", a - b);
}



Example 2 ( lamda in C# 2.0 )
public delegate void IntDelegate(int a,int b);
static void Main(string[] args)
{
    IntDelegate d;
    d = delegate(int a, int b) { Console.WriteLine("ADD = {0}", a + b); };
    d += delegate(int a, int b) { Console.WriteLine("SUB = {0}", a - b); };
    d(10, 20);
}
 

Example 3 ( lamda in C# 3.0)
public delegate void IntDelegate(int a, int b);   
static void Main(string[] args)
{
IntDelegate d;

d = (a, b) => { Console.WriteLine("ADD = {0}", a + b); };
d += (a, b) => { Console.WriteLine("SUB = {0}", a + b); };
d(10, 20);
}


This contribution is based on MSDN reference:
http://msdn.microsoft.com/en-us/library/bb397687.aspx

댓글 없음:

댓글 쓰기