Get instance name c#

This is now possible in C# 6.0:

Student myStudent = new Student("John");
var name = nameof(myStudent); // Returns "myStudent"

This is useful for Code Contracts and error logging as it means that if you use "myStudent" in your error message and later decide to rename "myStudent", you will be forced by the compiler to change the name in the message as well rather than possibly forgetting it.


This is not possible in C#. At runtime, the variable names will not even exist, as the JIT removes the symbol information.

In addition, the variable is a reference to the class instance - multiple variables can reference the same instance, and an instance can be referenced by variables of differing names throughout its lifetime.


This question is very old, but the answer changed with the release of .Net Framework 4.6. There is now a nameof(..) operator which can be used to get the string value of the name of variables at compile time.

So for the original question C# nameof(myStudent) // returns "myStudent"

Tags:

C#