How to get variable name of this?
var thename = new myclass();
Whereas I want the variable name "thename" inside myclass instance?
How to get variable name of this?
var thename = new myclass();
Whereas I want the variable name "thename" inside myclass instance?
What do you expect in the following scenario?
var theName = new MyClass();
var otherName = theName;
someList.Add(otherName);
The name(s) you're after don't belong to the instance but to the variables referencing it.
There are now three references pointing to the same instance. Two have distinct names, the third does not really have a name.
Inside a MyClass object, you can't know who's pointing at you. Heap objects themselves are always anonymous.
public class myclass()
{
public string VariableName { get; set; }
}
var theName = new myclass();
theName.VariableName = nameof(theName);
Instantiating the variable like this, it doesn't exist to have a name before you create the object. If you want to force every instance to populate that variable, then you can do something like this, but your code will be a little more verbose:
public class myclass()
{
public myclass(string variableName)
{
if (string.IsNullOrWhitespace(variableName)
{
throw new ArgumentNullException(nameof(variableName);
}
VariableName = variableName;
}
public string VariableName { get; private set; }
}
myclass theName;
theName = new myclass(nameof(myclass));
Of course, there's no guarantee that someone isn't passing in a different string.