Can I get the name of my object in C#?

We don't have a name of objects. In fact object's reference is assigned to the reference variable in order to access data via public methods/properties. If you wish to have the reference of an object within the instance method of that particular class then use this variable.

Class Boy
{   
    int age;
    public void setAge(int age)
    {
        this.age = age; 
    }
}

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"
    }
}

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.

Tags:

C#