How to determine the instant name of a class?

  • Thread starter Thread starter Ole
  • Start date Start date
O

Ole

If I define a class and create a instant of it like e.g.:

UserClass instantName = new UserClass();

how do I then determine the defined name "instantName" in the UserClass e.g.
in a method (or a property) like this:

public void userFunction()
{
string Var = new string();

Var = ???????; // instantName - how to determine this?
}

Thanks
Ole
 
I dont know if that can be done, you can get the class name by using the
GetType property tho, is this what you mean?

If you really do want to get the instance name could you explain what you
want it for because i have a feeling whatever you are trying to achieve,
this is not the right way to go about it.
 
Ole,

In your example "instantName" is just a reference variable which stores
a reference to your instance of UserClass.

An instance of UserClass could be referenced by more than one variable:
UserClass theInstance = new UserClass();
UserClass secondReference = theInstance;

Or it may just be part of an array and not be referenced by any variable
directly:
List<UserClass> list = new List<UserClass>();
list.Add(new UserClass());

If you want to store a name for the instance, you may just want add a
string property to the class.

Hope this helps.

Dan Manges
 
Ole,

You can't. If you want to name it, you would have to put it in a
dictionary, using the name of the variable that it refers to as a key.

The reason you can't do this is for this reason:

object a = new object();
object b = a;

So, considering a and b point to the same object, how do you know which
name to return? You can't. You would have to return every name, and quite
honestly, I don't see how knowing it could do you much good.

Hope this helps.
 
Thanks - I see the point. I'm actually using the class to define sensor
properties like serial number, calibration table, type etc. and in the
program i create an instance of each sensor used. The class calls another
class that saves the properies to a XML file and it was my intension to use
the instance name as the file name. I can off course set the file name in
the constructure like: UserClass instantName = new UserClass("instantName");
but this way I'll have to maintain two equal names - well it's no big deal
so that's what I will do - just curious if it was possible!

Thanks
Ole
 
Actually that is a better way to do it, even if the variable name
happens to be the same as the name of the sensor.

The data that the program handles should be separate from the control
structures of the program itself. When the sensor name is used as a
variable name, it's a part of the control structure, but when the sensor
name is used as a file name it's plain data.
 
Back
Top