# Tuesday, December 01, 2009
« ReSharper 5 won't run unit tests in Visu... | Main | Model mismatch »

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);
}
Tuesday, December 01, 2009 2:14:31 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview