// using System.Diagnostics.Contracts; using System.Linq.Expressions; static void ThrowIfNull<T>(Expression<Func<T>> expr) where T : class { // Contract.Requires(expr != null); // Contract.Requires(expr.Body.NodeType == ExpressionType.MemberAccess); if (((object)expr.Compile().Invoke()) == null) { throw new ArgumentNullException(((MemberExpression)expr.Body).Member.Name); } }
Then name it like this:
object someVariable = null; ThrowIfNull(() => someVariable); // will throw an ArgumentNullException // with paramName == "someVariable"
PS: I'm not sure if this will be a good idea: for the first construction of the expression tree, there will be overhead, and then compiling them each time this method is called, so that you can contain a null reference, and if so, then get the name of the variable. Something like void ThrowIfNull<T>(T arg, string paramName) not so good, but most likely will work much better!
stakx source share