Get the method name of the variable call from this method

I want to create an extension method for objects that check if an object is null and throw an exception, if any. However, I want to keep the original variable name. Can I somehow get it from the extension method? It is "cumbersome" to write customer.NotNull("customer") vs customer.NotNull() .

+4
source share
3 answers

No, unfortunately, you cannot. Variable names are not available at run time. However, you can use these expressions:

 void NotNull<T>(Expression<Func<T>> expression) { var me = expression.Body as MemberExpression; var name = me.Member.Name; var value = expression.Compile().Invoke(); ... } NotNull(() => customer); 
0
source
 // 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!

0
source

As the other said, but note that compiling the expression is something slow ... So this option gets the value as a parameter. You should write more, but for methods that are called a hundred times, this might be better.

 [DebuggerHidden] public static void NotNull<T>(T value, Expression<Func<T>> exp) where T : class { if (value != null) { return; } var body = exp.Body as MemberExpression; if (body == null) { throw new ArgumentException("Wrongly formatted expression"); } throw new ArgumentNullException(body.Member.Name); } 

Using:

 NotNull(str, () => str); 

[DebuggerHidden] is that the debugger will not go into this method. In the end, if the method throws, it is usually because you have passed, and not what the method has.

0
source

Source: https://habr.com/ru/post/1496445/


All Articles