views:

143

answers:

3

I have a Hashtable object which "names" or "map" various fields in a class with a string

ref class Interrupt{
  Interrupt(){
    this->type = 0;
    this->size = 0;
  }
  int type;
  int size;
}

Interrupt^ interrupt = gcnew Interrupt();

Hashtable^ map = gcnew Hashtable();
map->Add("InterruptType", interrupt->type);
map->Add("InterruptSize", interrupt->size);

this class is modified during runtime so type and size are both equals to 2.

further down the road I query my Hashtable but the values didn't change. I understand that it is because they are immutable. Is there a way I can specify my Hashtable to hold pointers to the fields of my class instead of storing the value of the reference?

I know I can modify class Interrupt to hold custom objects instead of raw int, but it would invole A LOT of refactoring.

+1  A: 

You could change it to have your Hashtable just hold a reference to your class itself (Interrupt) instead of the individual int values. This way, you could look up the int values based on the instance.

Reed Copsey
Good idea, this will require a large switch like statement to handle multiple fields however
Eric
Eric: It might be easier, in this case, to just make a custom class that provides the specific access you require instead of using a Hashtable. The class could hold the hashtable, and handle the "switching" appropriately.
Reed Copsey
+3  A: 

I understand that it is because they are immutable.

You understand wrong. Yes, integers are immutable. But the map values didn't change because integers are value types, and so were passed to the map's Add() method by value. In other words, the map holds a copy of the value passed to the Add() method rather than a reference to the variable passed to the method.

To fix this, you need to wrap your integers in a reference type (a class) and give the map a reference to the desired instance of that class. Then make sure that whenever you change your integers you're changing them as members of the correct instance.

Joel Coehoorn
A: 
Harper Shelby