0

How to get variable name of this?

var thename = new myclass();

Whereas I want the variable name "thename" inside myclass instance?

Satpal
  • 132,252
  • 13
  • 159
  • 168
David Ulvmoen
  • 87
  • 1
  • 3

2 Answers2

2

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.

H H
  • 263,252
  • 30
  • 330
  • 514
  • I get your point, I would like to have the original name that initiated the object. Is it possible to access stack variables to find their references for this? – David Ulvmoen Nov 02 '16 at 12:48
  • 1
    No, not reliably. Consider `someList.Add(new MyClass());` or the various ways you could use Linq to create objects. – H H Nov 02 '16 at 13:00
0
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.

krillgar
  • 12,596
  • 6
  • 50
  • 86