.NET, C#, Linq

Lambda expressions are not delegates

There is allot of confusion gotesing on in the .NET community when it comes to Lambda expressions.
Allot of blog posts out there claiming that Lambdas are simply another way to write delegates, or rather anonymous delegates.

Lambda expressions and delegates are two different things.

Delegates are always delegates.
Even anonymous delegates will always be turned into “normal” delegates in compiled code.

There is a one to one mapping in the source code to the compiled representation of a delegate.

Lambda expressions however, can be compiled into two different things.
They can be compiled into either delegates OR Linq Expression Trees.

In the cases where a lambda expression have been compiled into a delegate, then sure, they result in the same thing.

But since there is no way to know what a lambda expression will be compiled into just by looking at it.

SomeMethod( x => x.Substring(10) );

By looking at that code, one can ASSUME that it will execute the string method “Substring” once the lambda is invoked.
But there is no way to know for sure unless you know what argument type the “SomeMethod” has.

void SomeMethod (Func<string,string> func)

In this case we can be certain that the code we pass will be executed exactly as we intended.

But in this case:

void SomeMethod (Expression<Func<string,string>> exp)

We still pass the exact same snippet of code, but we can no longer be certain what will happen with the snipped of code we passed.
It MIGHT be executed the way we assume, but it might just as well be transformed into SQL code or even a Ruby snipped that is saved to disc and then executed in a Ruby engine.

So this is what I consider to be a huge difference between anonymous delegates and lambda expressions.

In the delegate case you can be 100% certain that the code will execute exactly as stated.
And in the lambda case, it might be executed outside of the .NET run-time in some completely different context.

Well, that’s all.


.NET, C#, Linq

Linq Expressions – Creating objects




So how is it done?
First we need a delegate declaration:


We will use this delegate in order to create our instances.

public static ObjectActivator<T> GetActivator<T>
    (ConstructorInfo ctor)
    Type type = ctor.DeclaringType;
    ParameterInfo[] paramsInfo = ctor.GetParameters();                  

    //create a single param of type object[]
    ParameterExpression param =
    Expression[] argsExp =
        new Expression[paramsInfo.Length];            

    //pick each arg from the params array 
    //and create a typed expression of them
        Expression index = Expression.Constant(i);
        Type paramType = paramsInfo[i].ParameterType;              

        Expression paramAccessorExp =
            Expression.ArrayIndex(param, index);              

        Expression paramCastExp =
            Expression.Convert (paramAccessorExp, paramType);              

        argsExp[i] = paramCastExp;

    //make a NewExpression that calls the
    //ctor with the args we just created
    NewExpression newExp = Expression.New(ctor,argsExp);                  

    //create a lambda with the New
    LambdaExpression lambda =

    //compile it
    return compiled;



//create an instance:
Created instance = createdActivator (123, "Roger");

 And that’s it.

Benchmark – Creating 1000 000 instances:

Activator.CreateInstance: 8.74 sec
Linq Expressions:         0.104 sec



.NET, C#, Linq

Linq Expressions – Calculating with generics

You can find the full code for this post here:

The .NET framework lacks support for calculating with generic types.

More about the problem can be found here:

built-in mathematical operations on generic types.”

Quirky to say the least..

One such solution exists here: http://www.codeproject.com/KB/cs/genericnumerics.aspx



We can produce delegates that performs the math operations for us.
Like this:

private static Func<T, T, T> CompileDelegate 
 (Func<Expression,Expression,Expression> operation) 
    //create two inprameters 
    ParameterExpression leftExp = 
 Expression.Parameter(typeof(T), "left");                   

    ParameterExpression rightExp = 
 Expression.Parameter(typeof(T), "right");                   

    //create the body from the delegate that we passed in 
    Expression body = operation (leftExp,rightExp);              

    LambdaExpression lambda = 

     //compile the lambda to a delegate 
    // that takes two args of T and returns T 
    return compiled; 




You can find the full code here:

This makes it possible to use code like this:

    if (!Number<T>.IsNumeric) 

    Number<T> v1 = arg1; 
    Number<T> v2 = arg2; 
    Number<T> v3 = arg3; 






.NET, C#, Linq

Linq Expressions – Access private fields


You will end up with something like this:

object res = field.GetValue (MyObj);



Here is how you do it:

  ParameterExpression param = 
  Expression.Parameter (typeof(T),"arg");  

  MemberExpression member = 
  Expression.Field(param, fieldName);   

  LambdaExpression lambda = 

  return compiled; 

So what does this method do?


The 3rd line is where we create our lambda expression.


Here is an example on how to use this code:

Person person = new Person(); 
person.FirstName = "Roger"; 
//typed access via delegate 
string result = getFirstName(person);


This approach is also much faster than Reflection.FieldInfo.

The Reflection.FieldInfo approach took 6.2 seconds to complete.
The Compiled lambda approach took 0.013 seconds to complete.
That’s quit a big difference.


Well, that’s all for now.



kick it on DotNetKicks.com

See also: