Latest on twitter:

Using .Net Expressions

One of the most powerfull parts of c# that totally went past me until a month or so ago, are Expressions. Simply put, if you create a lambda expression:

Func<int,int> square = x => x*x

You can call it as a function:

square(2); //returns 4

But if you forecefully declare it as an expression:

Expression<Func<int,int>> square = x => x*x

You have created an Expression of type lambdaExpression. It’s something that represents the function, but isn’t compiled yet:

square(2); //throws exception
Func<int,int> compiledSquare = square.compile();
compiledSquare(2); //returns 4

I first noticed the need for this when creating functions that needed to call the database using linq2sql. If along the way you create a function that accepts a delegate (Func<T> instead of Expression<Func<T>>) your queries suddenly won’t be translated to database queries anymore :(

So what can we do using expressions? well in my next posts I will describe how we can use it …

  1. …to pass a reference to a Member (i.e. a Method or Property) without having to use a string, and keeping it statically typed.
  2. …to create validation functions that will run both clientside in javascript and serverside as c#.
  3. …to have users create queries using a GUI interface that will be translated to sql but without having to concatenate sql queries by hand. This means that we can easily insert these queries in an existing pipeline.