Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of variable calling method from within that method

Tags:

c#

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

like image 241
user1323245 Avatar asked Aug 11 '13 18:08

user1323245


People also ask

What is the __ call __ method?

The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .

How do you get a function name inside a function in Python?

Method 3: Get Function Name in Python using __qualname__ attribute. The __qualname__ gives more complete information than __name__ and therefore can be more helpful in debugging. To extract the name from any object or class, you can also use its __qualname__ attribute.

How do you call a method in a string name?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How do you get a function from a string in Python?

String To Function Using The eval() Function In Python We can also use the eval() function to convert a string to a function. Here, the input string is the name of the function. In the eval() function, we will pass the name of the function and the ' () ' separated by the addition symbol ' + '.


1 Answers

No, unfortunately you can't. Variable names are not part available at run time. However, you can use expressions like this:

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);
like image 77
p.s.w.g Avatar answered Oct 12 '22 23:10

p.s.w.g