Created
November 11, 2010 12:21
-
-
Save jkells/672409 to your computer and use it in GitHub Desktop.
Using an expression to determine the name of a parameter.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.