Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the instance name of the object no the object type name in C# 4.0

Assume this type:

public class Car { } 

And I create an instance of that:

Car myCar = new Car();

Target target = new Target();
target.Model = myCar;

And this is another Type:

public class Target {

   public object Model { get; set; }

   string GetName(){

     //Use Model and return myCar in this Example
   }

}

As I showed in code the GetName method must use an object type (Model) and returned the name of instance that is myCar in this example? what is your suggestion is there any way to do this?

Update How about this:

public class Car {

  public string Title { get; set; }

}

And I pass to target: target.Model = Car.Title

And GetName() method returned Title ?

like image 316
Saeid Avatar asked Apr 18 '12 08:04

Saeid


3 Answers

Objects do not have a name, unless they explicitly have a way to store their name. myCar is a local variable - the object itself (the Car) does not know that you are referring to it by the name myCar. To illustrate:

Car myCar = new Car();
Car car2 = myCar;
Car car3 = myCar;

Now all three variables refer to the same Car.

If you want cars to have names, you could do

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

and then assign and read whatever name you want it to have.

like image 176
AakashM Avatar answered Nov 11 '22 08:11

AakashM


No, this is not possible. Why? Because myCar is only a name for your Car instance inside the scope which you set up the variable for. What gets saved to target.Model is a reference to the Car instance. So, after your sample code, both myCar and target.Model reference the same instance of Car, just with different names. The names themselves are rather unimportant to the execution of the program, it's just a trick we use to make talking about instances easier.

like image 44
Daren Thomas Avatar answered Nov 11 '22 09:11

Daren Thomas


There is no such thing as "name of the instance". What you're saying about is the name of the specific reference to the object; there could be many references to the same object, all with different names. Also, linking code and data (i.e. relying on the variable name) is a bad practice.

If you want Car to have some name, then name it explicitly:

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

Car myCar = new Car { Name = "myCar" };
like image 1
penartur Avatar answered Nov 11 '22 10:11

penartur