Search This Blog

Wednesday, February 15, 2012

Anonymous Type IN C# .NET3.0/4.0 Part2


Anonymous Functions

An anonymous function is an "inline" statement or expression that can be used wherever a delegate type is expected. You can use it to initialize a named delegate or pass it instead of a named delegate type as a method parameter.

There are two kinds of anonymous functions

1)   Lambda Expressions 
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the
lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can
be assigned to a delegate type as follows:
delegate int del(int i);
static void Main(string[] args)
{
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}


using System.Linq.Expressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<del> myET = x => x * x;
        }
    }
}
A lambda expression with an expression on the right side is called an expression lambda. Expression lambdas are used extensively in the construction of Expression Trees. An expression lambda returns the result of the expression and takes the following basic form:

(x, y) => x == y
 In the above example its take two parameter and compare and return a Boolean value

A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces:

delegate void TestDelegate(string s);
TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };
myDel("Hello");

note: Statement lambdas, like anonymous methods, cannot be used to create expression trees.

The general rules for lambdas are as follows:
·         The lambda must contain the same number of parameters as the delegate type.
·         Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter.
·         The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.

A standard query operator, the Count method
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
The compiler can infer the type of the input parameter, or you can also specify it explicitly. This particular lambda expression counts those integers (n) which when divided by two have a remainder of 1.
The following method will produce a sequence that contains all the elements in the numbers array that are to the left of the 9, because that is the first number in the sequence that does not meet the condition:
var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);

Anonymous Type IN C# .NET3.0/4.0 Part1


No comments :

Post a Comment