Ruby was the impetus for me to write a Guard clause that automatically get a parameter name from code. What do I mean by that? This passes:
[Test] public void Expression_guard_can_get_parameter_name_from_expression() { object address = null; Assert.Throws<ArgumentException>(() => Guard.AgainstNull(() => address), "The parameter address must not be null"); }
Notice how I didn’t specify the string “address” anywhere, the Guard.AgainstNull method got it from the expression () => address. I’m sure I’ve used constructs like this in C# before, but I haven’t written any yet. I wonder in what other ways I can abuse Expressions?
The implementation, that is not well tested by any means:
public static void AgainstNull<T>(Expression<Func<T>> expression) { AgainstNull(expression, "expression"); string paramName = ""; var memberExpression = expression.Body as MemberExpression; if (memberExpression != null) { paramName = memberExpression.Member.Name; } T instance = expression.Compile().Invoke(); AgainstNull(instance, paramName); }
Remember Me
a@href@title, strike
Powered by: newtelligence dasBlog 2.1.8102.813
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2010, Shawn Neal
E-mail