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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With