Over the past couple of years I’ve found myself doing more and more work involving reflection. Reflection is one of these things that I didn’t see that much use for at first, but now I see it everywhere.
One thing I’ve found really useful is using an expression as an argument to pass a property name – its not something you use every day but it definitely helps in refactoring and avoiding magic strings. The method I’ve been using is pretty simple, what I want to be able to do is call something like the following:
bool isValid = Person.IsPropertyValid(() => Person.Foreame);
Here everything is type safe – no magic strings!
To achieve this my IsPropertyValid method looks something like this:
public bool IsPropertyValid(Expression<Func> memberExpression)
var member = memberExpression.Body as MemberExpression;
if (member == null)
throw new ArgumentException("memberExpression does not equate to an actual member expression.");
Here the argument to IsPropertyValid is an expression – the type of which (T) is inferred from its usage. This member expression is then evaluated to return that members name.
The actual implementation of IsPropertyValid(string propertyName) can then do whatever you want with the property name.