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?
_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" };
bar from the instance in the code.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
}
}
Foo _bar2 = _bar;)?List<Foo>.Add(new Foo());