Skip to content

Instantly share code, notes, and snippets.

@jkells
Created November 11, 2010 12:21
Show Gist options
  • Save jkells/672409 to your computer and use it in GitHub Desktop.
Save jkells/672409 to your computer and use it in GitHub Desktop.
Using an expression to determine the name of a parameter.
using System;
using System.Linq.Expressions;
namespace ConsoleApplication1
{
public static class Assert
{
public static T NotNull<T>(Expression<Func<T>> expression) where T : class
{
if (expression.Body == null || expression.Body.NodeType != ExpressionType.MemberAccess)
throw new ArgumentException("Expression is not in the correct format.");
var memberExpression = expression.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("Expression is not in the correct format.");
var name = memberExpression.Member.Name;
var value = expression.Compile().Invoke();
if (value == null)
{
throw new ArgumentNullException(name);
}
return value;
}
}
public class Example
{
private object _dependency1;
private object _dependency2;
public Example(object dependency1, object dependency2)
{
_dependency1 = Assert.NotNull(() => dependency1);
_dependency2 = Assert.NotNull(() => dependency2);
}
}
class Program
{
static void Main(string[] args)
{
var x = new Example(new object(), null);
}
}
}
@jkells
Copy link
Author

jkells commented Nov 11, 2010

This sample will throw an exception ArgumentNullException. Value cannot be null. Paramater name: dependency2.

The name dependency2 is the name of the parameter to the method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment