This is not possible other than:
MyClass hello = new MyClass();
string name = nameof(hello)
or
MyClass hello = new MyClass(nameof(hello));
class MyClass {
private string Name;
public MyClass(string name){
this.Name = name;
}
public string getName(){
return this.Name;
}
}
But this leads to problems like this:
MyClass hello = new MyClass(nameof(hello));
test = hello;
test.getName(); // returns: hello;
Depends on what exactly you want, I would suggests the following instead:
Variable name
nameof
The easiest way would be use nameof (as shown in the other answer):
var varName = new MyClass();
return nameof(varName); // will return "varName"
the great thing is this will compile time be converted to "varName"
so you have the advantages of compile time checking but runtime speed of static string.
Disection of method
Another way to do it would be to disect the method and turn it into lambda experssion. In this lambda experssion you could search for the new variable declaration with the construction of this class. and then get the name of this variables. Im sorry but i have not much experience to show you an example for this. I would like you to refer to a duplicate post: Getting names of local variables (and parameters) at run-time through lambda expressions
Im not sure why you want to do this. since this is about how your code is named/programmed which doesn't realy matter during runtime. (then it only matters how it behaves.)
I would advice you to create an code analyzer instead for the roslyn compiler and add this one to your project.
Achitectural solution
The only way you would be able to get the behaviour you describe is to give the variable name to the class in the constructor:
var myVar = new MyClass(nameof(myVar));
var var2 = myVar;
var2.GetName(); // returns "myVar"
public class MyClass {
public MyClass(name){
this.createdWithName = name;
}
public string GetName(){
return this.createdWithName;
}
}
classname (Not variable name!)
A more handy thing to want, would be to get the name of the class. and you can do that in the following ways:
nameof
return nameof(MyClass); //will compile to "MyClass"
So compile time you have the luxury of MyClass checking for types and for easy refactoring. But runtime it will always return 'MyClass'.
Reflection
return this.GetType().Name;
Will return return the name of this class. This will, compared to nameof, not always return 'MyClass', but actually return the reall class of the instance. For example when you have the subclass MySubClass
this will return MySubclass
.