I was just taking a look to the powerful Expression Trees framework in the .NET Framework and I decided to create an example. The result: something that I will never use and I don’t recommend you, but in some way it’s illustrative.
It’s very common to use a class with properties to access the configuration. In this way, you benefit from the static check at compile time, assuming you are in a static language like C#. You can avoid the use of the same string in many places of the code and instead, you use a property like this:
public class AppConf
{
public static string SomeKey
{
get { return ConfigurationManager.AppSettings["SomeKey"]; }
}
}
Console.WriteLine("AppConf.SomeKey :- {0}", AppConf.SomeKey);
But still, there is a string, and while the string can be moved to a constant what if we want to avoid it? One possible solution is:
public class ExpAppConf
{
public static string SomeKey
{
get
{
return ConfigurationManager.AppSettings[
(new Func<Expression<Func<ExpAppConf, object>>, string>(
delegate(Expression<Func<ExpAppConf, object>> exp)
{
return ((MemberExpression)exp.Body).Member.Name;
})).Invoke(x => ExpAppConf.SomeKey)];
}
}
}
Console.WriteLine("ExpAppConf.SomeKey :- {0}", ExpAppConf.SomeKey);
I’m using Expression Trees, Lambda Expressions and Anonymous Methods, but don’t worry, if you understand all the “trivial-tree paragraph” MVVM blog post out there, you will be fine here.
Which do you think are the possible drawbacks?













6 Comments
“Which do you think are the possible drawbacks?”
A headache for whoever has to maintain that.
Amen. Think you’re trying to solve a problem that doesn’t really exist? In reality the string references only usually exist in a single class anyway.
Lots of Irritating Superfluous Parentheses
despite the fact that it’s not lisp
Cool to know about this C# feature I didn’t know about but, really, how’s that better than using constant strings? This adds quite a lot of complexity for no real benefit.
Hi @Andrea, in this particular case, the only advantage I can see is in the automatic refactor case, since all the references are static type checked. One example of a good application for expression trees is in the Fluent NHibernate library IMO.
@Gubatron, I agree with you. Seems that similar task in Haskell or Lisp is more legible than to be written in C#. So, I prefer to use C# on the classical way, as imperative descendant language. Also C++0x lambda expressions are more clear to read, so a C++0x lambda expression like:
[](int x) -> int { return x * x; };Is more legible than the C# one, and expression tree is really a headache…
One Trackback
Social comments and analytics for this post…
This post was mentioned on Twitter by aldenml: @gubatron C#, Expression Trees, Lambda Expressions and Anonymous Methods http://bit.ly/aABbJb...