Get the parameter name and value from a lamba expression
I’ve recently been working on a design-by-contract library for a new project and thought it would be worth blogging some of the cooler methods as they might be useful.
In this blog I’m going to show an implementation of a Require IsNotNull method which internally gets the parameter name and value from a passed in lambda expression and uses this information to throw an exception with a useful error message if the parameter is null.
The Require IsNotNull method
The Require IsNotNull method is use to check a pre-condition before running a method.
For example, if your method relies on a parameter not being null, the method would throw an exception if a null is passed in.
Here is an example usage of the method:
- public void MyMethod(string myParameter)
- {
- Require.IsNotNull(() => myParameter);
- // method implementation ommited.
- }
As you can see, the parameter is passed in as an expression: () => myParameter.
The exception message thrown could be something like: the parameter named ‘myParameter’ cannot be null.
How it works.
Firstly we need to get the parameter name so we can build up a useful exception message.
This is done through the use of expressions.
- public static string GetParameterName<TParameter>(Expression<Func<TParameter>> parameterToCheck)
- {
- MemberExpression memberExpression = parameterToCheck.Body as MemberExpression;
- string parameterName = memberExpression.Member.Name;
- return parameterName;
- }
As you can see, the body of the parameter expression is cast and evaluated as a member expression, then the name of the parameter is easily retrieved.
The next task is to get the value of the parameter so we can ascertain whether it is null.
- public static TParameter GetParameterValue<TParameter>(Expression<Func<TParameter>> parameterToCheck)
- {
- TParameter parameterValue = (TParameter)parameterToCheck.Compile().Invoke();
- return parameterValue;
- }
As you can see, the parameter expression is compiled and then invoked and the resulting value is returned.
Putting it all together
Ok, the following is quite a crude example but it should give a fairly good idea of how useful this can be:
- public static void IsNotNull<TParameter>(Expression<Func<TParameter>> parameter)
- {
- string parameterName = ExpressionHelper.GetParameterName(parameter);
- var parameterValue = ExpressionHelper.GetParameterValue(parameter);
- if (parameterValue == null)
- {
- throw new Exception(string.Format("the parameter named ‘{0}’ cannot be null", parameterName));
- }
- }
Obviously if you use this approach you should also check the parameter expression passed is not null and the exception handling should be cleaned up and refactored.
I hope this is useful.
Kind Regards,
Sean McAlinden