Friday, 28 September 2012

Expression Tree in c#


Expression trees represent code in a tree-like data structure, where each node is an expression. You can compile and run code represented by expression trees. This enables dynamic modification of executable code.

When a lambda expression is assigned to a variable of type Expression, the compiler emits code to build an expression tree that represents the lambda expression. The Expression tree can be parsed as shown below. Next come the compiling of the expression tree and then execute. Only expression trees that represent lambda expressions can be executed. Expression trees that represent lambda expressions are of type LambdaExpression or Expression. To execute these expression trees, call the Compile method to create an executable delegate, and then invoke the delegate.

     //Creating Expression Trees from Lambda Expressions
     Expression<Func<int, bool>> lambda = num => num < 5;

     //Parsing Expression Trees
      ParameterExpression param = (ParameterExpression)lambda.Parameters[0];
      BinaryExpression operation = (BinaryExpression)lambda.Body;
      ParameterExpression l = (ParameterExpression)operation.Left;
      ConstantExpression r = (ConstantExpression)operation.Right;

      Console.WriteLine("Decomposed expression: {0} => {1} {2} {3}",
                        param.Name, l.Name, operation.NodeType, r.Value);
           
      // Compiling the expression tree into a delegate.
      Func<int, bool> result = lambda.Compile();

      // Invoking the delegate and writing the result to the console.
      Console.WriteLine("Result for execution - {0}",result(4));



 To create expression trees by using the API, use the Expression class. This class contains static factory methods that create expression tree nodes of specific types, for example, ParameterExpression, which represents a variable or parameter, or MethodCallExpression, which represents a method call. ParameterExpression, MethodCallExpression, and the other expression-specific types are also defined in the System.Linq.Expressions namespace. These types derive from the abstract type Expression. Now we will see how we can create the Above stated expression unsing Expression class.

//Creating Expression Trees by Using the API
ParameterExpression numParam = Expression.Parameter(typeof(int), "num");
ConstantExpression five = Expression.Constant(5, typeof(int));
BinaryExpression numLessThanFive = Expression.LessThan(numParam, five);
Expression<Func<int, bool>> lambda1 = Expression.Lambda<Func<int, bool>>(
                    numLessThanFive,
                    new ParameterExpression[] { numParam });

Once you keep a breakpoint you see the following –



In .NET Framework 4, the expression trees API also supports assignments and control flow expressions such as loops, conditional blocks, and try-catch blocks. By using the API, you can create expression trees that are more complex than those that can be created from lambda expressions by the C# and Visual Basic compilers.


Expression trees should be immutable. This means that if you want to modify an expression tree, you must construct a new expression tree by copying the existing one and replacing nodes in it. You can use an expression tree visitor to traverse the existing expression tree.

Use Expression Trees to Build Dynamic Queries

In LINQ, expression trees are used to represent structured queries that target sources of data that implement IQueryable. For example, the LINQ to SQL provider implements the Iqueryable interface for querying relational data stores. The C# and Visual Basic compilers compile queries that target such data sources into code that builds an expression tree at runtime. The query provider can then traverse the expression tree data structure and translate it into a query language appropriate for the data source.
Expression trees are also used in LINQ to represent lambda expressions that are assigned to variables of type Expression.
The following example shows you how to use expression trees to construct a query against an IQueryable data source and then execute it. The code builds an expression tree to represent the following query:

//Creating the follwoinh C# Query :
companies.Where(company => (company.ToLower() == "coho winery" || company.Length > 16)).OrderBy(company => company)
           
// The IQueryable data to query.
IQueryable<String> queryableData = companies.AsQueryable<string>();

// Compose the expression tree that represents the parameter to the predicate.
ParameterExpression pe = Expression.Parameter(typeof(string), "company");

// ***** Where(company => (company.ToLower() == "coho winery" || company.Length > 16)) *****

// Create an expression tree that represents the expression 'company.ToLower() == "coho winery"'.
Expression left = Expression.Call(pe, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
Expression right = Expression.Constant("coho winery");
Expression e1 = Expression.Equal(left, right);

// Create an expression tree that represents the expression 'company.Length > 16'.
left = Expression.Property(pe, typeof(string).GetProperty("Length"));
right = Expression.Constant(16, typeof(int));
Expression e2 = Expression.GreaterThan(left, right);

// Combine the expression trees to create an expression tree that represents the
// expression '(company.ToLower() == "coho winery" || company.Length > 16)'.
Expression predicateBody = Expression.OrElse(e1, e2);

// Create an expression tree that represents the expression
// 'queryableData.Where(company => (company.ToLower() == "coho winery" || company.Length > 16))'
MethodCallExpression whereCallExpression = Expression.Call(
                typeof(Queryable),
                "Where",
                new Type[] { queryableData.ElementType },
                queryableData.Expression,
                Expression.Lambda<Func<string, bool>>(predicateBody, new ParameterExpression[] { pe }));
// ***** End Where *****

// ***** OrderBy(company => company) *****
// Create an expression tree that represents the expression
// 'whereCallExpression.OrderBy(company => company)'
MethodCallExpression orderByCallExpression = Expression.Call(
                typeof(Queryable),
                "OrderBy",
                new Type[] { queryableData.ElementType, queryableData.ElementType },
                whereCallExpression,
                Expression.Lambda<Func<string, string>>(pe, new ParameterExpression[] { pe }));
// ***** End OrderBy *****

// Create an executable query from the expression tree.
IQueryable<string> results = queryableData.Provider.CreateQuery<string>(orderByCallExpression);

// Enumerate the results.
foreach (string company in results)
     Console.WriteLine(company);

Monday, 24 September 2012

Static class vs Static member vs Singleton

Static class vs Static member variable or method
Let's start with the memory first. Whenever a process is loaded in the RAM, we can say that the memory is roughly divided into three areas (within that process): Stack, Heap, and Static (which, in .NET, is actually a special area inside Heap only known as High Frequency Heap).
The static part holds the “static” member variables and methods. What exactly is static? Those methods and variables which don't need an instance of a class to be created are defined as being static
class MyClass
{
    public static int a;
    public static void DoSomething();
}
These member variables and methods can be called without creating an instance of the enclosing class. E.g., we can call the static method DoSomething() as:
MyClass.DoSomething();
We don't need to create an instance to use this static method.
MyClass m = new MyClass();
        m.DoSomething();
        //wrong code. will result in compilation error.
An important point to note is that the static methods inside a class can only use static member variables of that class. Let me explain why:
Suppose you have a private variable in MyClass which is not static:
class MyClass
{
    // non-static instance member variable
    private int a;
    //static member variable
    private static int b;
    //static method
    public static void DoSomething()
    {
        //this will result in compilation error as “a” has no memory
        a = a + 1;
        //this works fine since “b” is static
        b = b + 1;
    }
}
Now, we will call the DoSomething method as:
MyClass.DoSomething();
Note that we have not created any instance of the class, so the private variable "a" has no memory as when we call a static method for a class, only the static variables are present in the memory (in the Static part). Instance variables, such as “a” in the above example, will only be created when we create an instance of the class using the “new” keyword, as:
MyClass m = new MyClass();  //now “a” will get some memory
But since we haven’t created an instance yet, the variable “a” is not there in the process memory. Only “b” and “DoSomething()” are loaded. So when we call DoSomething(), it will try to increment the instance variable “a” by 1, but since the variable isn’t created, it results in an error. The compiler flags an error if we try to use instance variables in static methods.
Now, what is a static class? When we use the static keyword before a class name, we specify that the class will only have static member variables and methods. Such classes cannot be instantiated as they don’t need to: they cannot have instance variables. Also, an important point to note is that such static classes are sealed by default, which means they cannot be inherited further. The static member is callable on a class even when no instance of the class has been created. . Only one copy of a static member exists, regardless of how many instances of the class are created.
This is because static classes have no behavior at all. There is no need to derive another class from a static class (we can create another static class).
Why do we need static classes? As already written above, we need static classes when we know that our class will not have any behavior as such. Suppose we have a set of helper or utility methods which we would like to wrap together in a class. Since these methods are generic in nature, we can define them all inside a static class. Remember that helper or utility methods need to be called many times, and since they are generic in nature, there is no need to create instances. E.g., suppose that you need a method that parses an int to a string. This method would come in the category of a utility or helper method.
So using the static keyword will make your code a bit faster since no object creation is involved.
An important point to note is that a static class in C# is different from one in Java. In Java, the static modifier is used to make a member class a nested top level class inside a package. So using the static keyword with a class is different from using it with member variables or methods in Java (static member variables and methods are similar to the ones explained above in C#).
Please see the following link for details:
Also, the static keyword in C++ is used to specify that variables will be in memory till the time the program ends; and initialized only once. Just like C# and Java, these variables don’t need an object to be declared to use them. Please see this link for the use of the static keyword in C++:
Writing about the const keyword brings me to a subtle but important distinction between const and readonlykeywords in C#: const variables are implicitly static and they need to be defined when declared. readonlyvariables are not implicitly static and can only be initialized once.
E.g.: You are writing a car racing program in which the racing track has a fixed length of 100 Km. You can define a const variable to denote this as:
private const int _trackLength = 100;
Now, you want the user to enter the number of cars to race with. Since this number would vary from user to user, but would be constant throughout a game, you need to make it readonly. You cannot make it a const as you need to initialize it at runtime. The code would be like:

public class CarRace
{
    //this is compile time constant
    private const int _trackLength = 100;
    //this value would be determined at runtime, but will
    //not change after that till the class's
    //instance is removed from memory
    private readonly int _noOfCars;

    public CarRace(int noOfCars)
    { }

    public CarRace(int noOfCars)
    {
        ///<REMARKS>
        ///Get the number of cars from the value
        ///use has entered passed in this constructor
        ///</REMARKS>
        _noOfCars = noOfCars;
    }
}

Singleton vs Static class. 

Both has same purpose to make sure only one instance of the object exists throughout the Application Domain. However Singleton has following advantage over usage of static class.

An object of singleton class can be passed to method but we can not pass the static class to method. 

It is easy to change the logic of creating the object with some pooling mechanism but its very difficult to implement pooling mechanism with static class. 

Singleton class does not say any restriction of Inheritence.So we should be able to do this as long as subclass is also inheritance.There's nothing fundamentally wrong with subclassing a class that is intended to be a singleton. but We can not inherit Static class to another Static class in C#. 

Singletons allow you to reuse code and control object state much easier. This improves code-sharing, and can result in a far cleaner body of code. With less code, your programs will usually have fewer bugs and will be easier to maintain. 

Anonymous methods


1. Before c# 2.0, delegate could be declare only using named methods.
2. C# introduced anonymous methods and same can be used for delegate.

// Create a handler for a click event
button1.Click += delegate(System.Object o, System.EventArgs e)
                   { System.Windows.Forms.MessageBox.Show("Click!"); };

or
// Create a delegate instance
delegate void Del(int x);

// Instantiate the delegate using an anonymous method
Del d = delegate(int k) { /* ... */ };

3. Benefit -We reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.
4. Another good example would be when launching a new thread. This class creates a thread and also contains the code that the thread executes, without the need for creating an additional method for the delegate.
void StartThread()
{
    System.Threading.Thread t1 = new System.Threading.Thread
      (delegate()
            {
                System.Console.Write("Hello, ");
                System.Console.WriteLine("World!");
            });
    t1.Start();
}
5. The scope of the parameters of an anonymous method is anonymous-method-block.
6. It is an error to have a jump statement, such as goto, break, or continue, inside the anonymous method block whose target is outside the block. Similarly it is also an error to have a jump statement, such as goto, break, or continue, outside the anonymous method block whose target is inside the block.
7. The local variables and parameters whose scope contain an anonymous method declaration are called outer or captured variables of the anonymous method. For example, in the following code segment, n is an outer variable:
int n = 0;
Del d = delegate() { System.Console.WriteLine("Copy #:{0}", ++n); };

8.  Unlike local variables, the lifetime of the outer variable extends until the delegates that reference the anonymous methods are eligible for garbage collection. A reference to n is captured at the time the delegate is created.
9. An anonymous method cannot access the ref or out parameters of an outer scope.
10. Two ways of instantiating a delegate:
·             Associating the delegate with an anonymous method.
·             Associating the delegate with a named method (DoWork).
In each case, a message is displayed when the delegate is invoked.
// Declare a delegate
delegate void Printer(string s);

class TestClass
{
    static void Main()
    {
        // Instatiate the delegate type using an anonymous method:
        Printer p = delegate(string j)
        {
            System.Console.WriteLine(j);
        };

        // Results from the anonymous delegate call:
        p("The delegate using the anonymous method is called.");

        // The delegate instantiation using a named method "DoWork":
        p = new Printer(TestClass.DoWork);

        // Results from the old style delegate call:
        p("The delegate using the named method is called.");
    }

    // The method associated with the named delegate:
    static void DoWork(string k)
    {
        System.Console.WriteLine(k);
    }
}

Output
The delegate using the anonymous method is called.
The delegate using the named method is called.