1

I have a class foo as such:

    class Foo
    {

    }

and I have initialized an instance as

    Foo _bar =new Foo();

How do I get the name of the variable (_bar for the purposes of this question) within the class Foo?

3
  • 3
    Which name would you like to retrieve if you have more than one reference to your instance (i.e. Foo _bar2 = _bar;)? Commented May 7, 2011 at 13:22
  • ...or List<Foo>.Add(new Foo()); Commented May 7, 2011 at 13:31
  • @Josef I guess I hadn't tought about that, because thats not something that would happen in this particular case that I'm dealing with. Commented May 7, 2011 at 13:34

2 Answers 2

2

_bar is not a name of the instance of the class. It's a name of a variable that holds a reference to that instance. The instance doesn't know anything about what variables hold references to it, so what you want to do is impossible.

If you want your instances to have names, you would have to add a property to your class, e.g. like this:

class Foo
{
    public string Name { get; set; }
}

and use it like this:

Foo bar = new Foo { Name = "baz" };
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks... thats how i do it now, i was wondering if there was a easier way to do this...
The snippet doesn't solve anything, the "bar" reference name still can't be retrieved in any way. This is pretty fundamental, one of the most important jobs of the jitter optimizer is to get rid of explicit locations for object reference variables and store them in a CPU register instead. Makes code a lot faster.
@Hans, what I meant to show by the code is that you can use a property to hold a name of an instance. Of course you're right that there is no way to get the name bar from the instance in the code.
0

You can include "Foo _bar =new Foo();" inside another class and then find it by reflection and then set an elementname property inside class Foo again by reflection.

class Foo
{

public string ElementName {get; set;}


}

public class MyParent
{
Foo _bar =new Foo();

public MyParent()
{
//You can find Foo(s) here and then set ElementName of Each foo by reflection
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.