Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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 ?

like image 394
rock Avatar asked Sep 03 '12 01:09

rock


2 Answers

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.

like image 152
Marc Gravell Avatar answered Oct 04 '22 05:10

Marc Gravell


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"
    }
}
like image 43
Navin Kumar Avatar answered Oct 04 '22 06:10

Navin Kumar