Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get instance name c#

Tags:

c#

Maybe, this question is stupid, but in my specific situation i want to get instance name, so what i mean :

class Student
{
     private string name {get; private set;}

     public Student(string name) 
     {
         this.name = name 
     }

     public getInstanceName() 
     {
        //some function
     }

}

so when i make an student

   Student myStudent = new Student("John");

it's stupid but i want this

 myStudent.getInstanceName(); // it should return 'myStudent'
like image 829
Yoan Dinkov Avatar asked May 03 '13 16:05

Yoan Dinkov


2 Answers

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.

like image 63
elexis Avatar answered Oct 22 '22 14:10

elexis


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.

like image 10
Reed Copsey Avatar answered Oct 22 '22 12:10

Reed Copsey