how to reference object as integer

  • Thread starter Thread starter samlee
  • Start date Start date
S

samlee

// create an object
Control obj=new Control();
// How to write c# code to achieve the following pseudo code?
// use an integer to represent an obj
int temp=(int)obj;
// later recover original object
Control obj1=(Control)temp;

TIA
 
NEVER DO SOMETHING LIKE THIS!

The CLR can move the objects for memory - optimation, and if you persit a
pointer it need additional coding (e.g fixed - statement). This shall only
be done in the case of InterOp!

If you want just to be able to get an integer to repesent your object, you
could do the following:

class ControlIntConverter
{
ArrayList list = new ArrayList();

public int RegisterControl(Control ctl)
{
return list.Add(ctl);
}

public Control GetRegistredControl(int handle)
{
return list[handle] as Control;
}
}

BUT: The integers are only valid as long the app is running! And if so, you
could also save the Reference itself, maybe re-think your design!

GP
 
Rob Tillie said:
Why the hell would you want to do that? :|
If it works, it should work how you did it.
I think you want the pointer to the object, so maybe something like:
int temp = (int) &obj;

I think this way you never get a pointer to an object.
You only get a pointer to an int, which actually is not
there!

Instead, you may try to use a GCHandle structure,
which you can convert to an IntPtr and further
to an int.

HTH,
Maciej
 
Back
Top