Using static reflection is deceptively simple: Take an expression and retrieve its reflection info. In other words it does what reflection does, but without needing to reflect dynamically, instead taking advantage of the fact that the information required is already available in the expression itself. That is, by virtue of accessing a member or artefact, the runtime has already done the legwork of matching that up to the reflection info, and if we simply examine the expression tree then we can retrieve that info from it.

Because it’s both so simple and so useful, I’ve rolled a helper class called StaticReflection.cs (as I’m sure countless others have done) to get quick access to member definitions – specifically, their names and types.

The magic fairydust is mostly contained in the System.Linq.Expressions.Expression<T> type. Expressions can be any form of code expression, but the StaticReflection class really only makes sense for expressions that identify type- or instance members, etc. So then, Expression<T> is a kind of wrapper for some arbitrary code expression (for example, an expression that represents a call to the Name property of the object contained in _MyCustomer is shown below) – and lets us supply such expressions as arguments to functions (or store them in fields or locals, or whatever).

() => _MyCustomer.Name

It’s worth noting that we’re sending through the _MyCustomer.Name expression itself, as opposed to evaluating the property and sending its result value. This effectively means that the instances used to access instance members are quite arbitrary (at least for the current purpose, i.e. as long as you’re not going to be evaluating the expression on the instance) – insomuch as the instance serves merely as a “pointer” to the type, and something like the following line would be perfectly legal and valid.

StaticReflection.GetMethodName(() => ((string)null).Trim())

The “T” in Expression<T> then indicates the form of the member definition that the expression represents, in the case of StaticReflection being either Func<T> or Action (the latter to support void functions. So far I’ve only had need of those two, since something like string Test( string value ); (which is really a Func<T, TResult>) is still assignable to Expression<Func<T>>. As an aside – Func<T> is useful in that you can give it an expression for any function, and you get static access to the return type of the function for free (useful in a number of scenarios, but not used in this particular class).

For the purpose of the StaticReflection class, all we really want from the expression wrapper is the Expression.Body member, which will point us to the actual “content” of the expression, represented by the base Expression type. It is useful at this point to note that Body could be a complex expression tree, at which point the superficial code in StaticReflection will most probably fail miserably. As previously alluded to, this code really kind of depends on the expressions being representative of simple member access calls (methods, properties, etc.) – Once we have a reference to the member body, all that remains is for us to know what kind of a body we are dealing with, and this is as simple or as complex as the body that was supplied to the function in the first place.

With the assumption that it will be a member expression, it becomes very simple indeed. To this end [of simplifying the usage] I use both a GetMethodName( Expression<Func<T>> expression ) and a GetPropertyName( Expression<Func<T>> expression ) method definition (even though they accept the same parameters) – specifically so that the code can assume in the first case that it is dealing with a MethodCallExpression, and in the second case a MemberExpression, which then in turn allows us to access members appropriate to those body types. (Note: The easiest way to get to this point, is to construct a function with an expression parameter of the form required to receive your expression, then to put a break point in it and analyse the body in debug mode, which would give you type information that you can then use to further your purpose.)

public static MethodInfo GetMethodInfo<T>( Expression<Func<T>> expression ) {
   MethodCallExpression body = (MethodCallExpression)expression.Body;
   return body.Method;
}

public static PropertyInfo GetPropertyInfo<T>( Expression<Func<T>> expression ) {
   MemberExpression body = (MemberExpression)expression.Body;
   return (PropertyInfo)body.Member;
}

There’s still a lot more you can do with expressions over and above static reflection (which actually just barely scratches the surface). For instance you can call .Compile() to receive an actual delegate (e.g. Func<T>) to the member represented by the expression (on which you can then call .Invoke(), .BeginInvoke(), etc.) Even through the reflection info provided by the functions in StaticReflection, you could get/set property values, invoke methods, etc. The true power of expressions, however, lies in their very dynamic nature – and is probably best illustrated by LINQ. Here, a chain of expressions can be analysed and “rebuilt” in an optimised way, before the expression is compiled and executed (see: deferred execution). Thus something like:

target.GetTypes().Where(o => o.IsPublic).Where(o => o.IsAbstract)

… in actuality becomes:

target.GetTypes().Where(o => o.IsPublic &amp;&amp; o.IsAbstract)

… at the point of execution, even though the two chaining parts could be added by different components altogether. Every developer needs to get a grasp on the concept of deferred execution at least to the extent that it makes sense when to use it and when to force expression evaluation (by calling .ToArray(), .ToList() or similar) 😉

So how would we use the StaticReflection class then?… well its initial intention is simply to rid you of the need to use string literals to refer to members. This means that:

public string MyProperty {
   get { return _MyProperty; }
   set {
      _MyProperty = value;
      OnPropertyChanged("MyProperty");
   }
}

… will instead become:

public string MyProperty {
   get { return _MyProperty; }
   set {
      _MyProperty = value;
      OnPropertyChanged(StaticReflection.GetPropertyName(() => MyProperty));
   }
}

… and with a tiny addition to your OnPropertyChanged function, could become:

public string MyProperty {
   get { return _MyProperty; }
   set {
      _MyProperty = value;
      OnPropertyChanged(() => MyProperty);
   }
}

… which I’m sure you’ll agree makes a lot more sense, as it is now safe to refactor, will get validated by the compiler (i.e. will not compile if you’ve misspelt the identifier), etc.

The class is downloadable here.