Code as Data in C# – Taking advantage of Expression Trees In Everyday Programming
In C# 3.0 a lambda expression can be converted into either an expression tree or a delegate ..former of which lets you treat code as data ..this mechanism is source of all the coolness behind linq to sql .
But this is doesnt have to be limited to frameworks, You can take advantage of this mechanism in your day
to day coding .. here are just two examples of the stuff I’ve used this in the past ( examples below are made up equivalents)
Builders :
Lets say you are writing a weekly activity recorder , the traditional ( boring ..) way of creating it would be
WeeklyActivityRecorder weeklyActivities = new WeeklyActivityRecorder ();
weeklyActivities .AddActivity( new Activity{Day = DayOfWeek.Monday , Activity = "Lawn Moving" });
weeklyActivities .AddActivity( new Activity{Day = DayOfWeek.Tuesday , Activity = "Cooking" });
The ” Code as Data ” way would be ..
WeeklyActivityRecorder weeklyActivities = new WeeklyActivityRecorder () .WithActivities( Monday => "Lawn Moving",Tuesday => "Cooking");
This looks more readable ( and fun
).. and there is very little work involved to actually achieve this
public static WeeklyActivityRecorder WithActivities(this WeeklyActivityRecorder recorder, params Expression<Func<DayOfWeek, string>>[] activities)
{
foreach( var activity in activities )
{
LambdaExpression expression = activity;
ConstantExpression activity= expression.Body as ConstantExpression;
DayOfWeek day = expression.Parameters[0];
recorder.AddActivity(new Activity {DayOfWeek = day , Activity = activity});
}
return recorder ;
}
Here I define a new extension method on WeeklyActivityRecorder which takes varargs lambda expressions
I then parse the lambda expression to create the appropriate activity , pretty straightforward stuff.
The second example is creating a hibernate criteria from expression tree
Once again the *old* way of querying by property would be by passing in the property by string
protected IList<T> _FindByProperty(string propertyName , object value)
{
return _hibernateTemplate.Execute(
session => session.CreateCriteria(typeof(T)).
Add(Expression.Eq(propertyName, value)).List())
.Cast<T>().ToList();
}
Code is obviously fragile since you have to use strings as property names which cannot be checked at compile time..
So instead of calling that method directly we could call it through a method which accepts an expression instead of string
</pre>
protected IList<T> _FindByProperty<TResult>(Expression<Func<T, TResult>> expression, TResult value)
{
return _FindByProperty((expression.Body as MemberExpression).Member.Name, value);
}
<pre>
The Above method could now be called as
IList<User> costCenters = _FindByProperty( user=> user.Name, "surya");
Existence of property “Name” is now checked at compiled time ..Although this technique is powerful, it feels
limited when compared to what you can do in LISP dialects.
Filed under: Uncategorized | 1 Comment
Nice article! Really helpful.