Let us say I have the following class..
Class Boy
{
public void hello()
{
Console.WriteLine("Hello!");
}
static void Main(String[] args)
{
Boy a = new Boy();
a.hello();
}
}
I know that the variable 'a' is a reference variable of type 'Boy'. The keyword 'new' created an object of 'Boy' assigning the address of it to the variable 'a'.
Now, is it possible for me to get the name of my object. Does an object in C# have a name at all ?
I'm guessing you are referring to the name of the variable, "a". Well, the thing is: that isn't the name of the object - objects don't have names. Further, an object can have zero one or multiple references to it, for example:
var x = new SomeType(); // a class
var y = x;
Here both x and y refer to the same object. Equally:
new SomeType();
doesn't have any references to it, but is still an object. Additionally, method variables (locals) don't actually have names in IL - only in c# (for contrast, fields do have names). So new SomeType().WriteName();
would make no sense.
So no: there is no sane way of getting the name of the variable from an object reference.
If you want the object to have a name, add a Name
property.
There are some fun ways to get the name of a variable of field using expression trees, but I don't think that is useful to what you are trying to do.
class Boy
{
public void hello()
{
Console.WriteLine("Hello!");
}
static void Main(String[] args)
{
Boy a = new Boy();
a.hello();
Type objtype = a.GetType();
Console.WriteLine(objtype.Name); // this will display "Boy"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With