Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get variable name using reflection? [duplicate]

Tags:

c#

reflection

For example,

static void Main() {     var someVar = 3;      Console.Write(GetVariableName(someVar)); } 

The output of this program should be:

someVar 

How can I achieve that using reflection?

like image 836
Eran Betzalel Avatar asked Apr 02 '10 10:04

Eran Betzalel


People also ask

Can we get variable name in Java?

A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign " $ ", or the underscore character " _ ". The convention, however, is to always begin your variable names with a letter, not " $ " or " _ ".

Can we print variable name in Java?

In short. You can't print just the name of a variable.

What is C# reflection?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.


1 Answers

It is not possible to do this with reflection, because variables won't have a name once compiled to IL. However, you can use expression trees and promote the variable to a closure:

static string GetVariableName<T>(Expression<Func<T>> expr) {     var body = (MemberExpression)expr.Body;      return body.Member.Name; } 

You can use this method as follows:

static void Main() {     var someVar = 3;      Console.Write(GetVariableName(() => someVar)); } 

Note that this is pretty slow, so don't use it in performance critical paths of your application. Every time this code runs, several objects are created (which causes GC pressure) and under the cover many non-inlinable methods are called and some heavy reflection is used.

For a more complete example, see here.

UPDATE

With C# 6.0, the nameof keyword is added to the language, which allows us to do the following:

static void Main() {     var someVar = 3;      Console.Write(nameof(someVar)); } 

This is obviously much more convenient and has the same cost has defining the string as constant string literal.

like image 80
Steven Avatar answered Sep 22 '22 16:09

Steven