Reputation: 139
So I need a list (or similar data structure) that always holds the current value for a given variable, once it has been added. This is what currently occurs (in simpler/pseudo code):
intValue = 5;
intList.Add(intValue);
Print intList[0].toString();
Prints "5"
intValue++;
Print intList[0].toString();
Still Prints "5" when I want it to print intValue's new value, "6".
Basically the list needs to store a reference to intValue (I think that's the correct terminology) and not it's actual value. Thanks for your time.
Upvotes: 0
Views: 220
Reputation: 2103
Since you will need to store the reference instead of the value of the variables, you can store the pointers. You will need to use unsafe
keyword to use pointers in C#.
unsafe
{
int intVal=5;
List<IntPtr> intList = new List<IntPtr> ( );
intList.Add ( new IntPtr ( &intVal ) );
MessageBox.Show ( ( *( ( int* ) ( intList[0].ToPointer ( ) ) ) ).ToString ( ) );
intVal++;
MessageBox.Show ( ( *( ( int* ) ( intList[0].ToPointer ( ) ) ) ).ToString ( ) );
}
Upvotes: 1
Reputation: 1831
This is because in C#, int
is a value type instead of reference type. When you write
intValue = 5;
intList.Add(intValue);
you add a copy to intValue
, and not a reference to the variable itself. What you want is to add a reference to the variable intValue
to intList
. What you can do is wrap your int
values in a class of you own (which is a reference type).
Upvotes: 3
Reputation: 10604
Your question is pretty similar to the following:
How to get a list of mutable strings?
Change the SortOfMutableString
implementation in the accepted answer to store int
values instead of string
and you'll get the desired effect.
Also, check out Jon Skeet's answer there. This is very important to fully understand the consequences of such kind of solutions.
Upvotes: 8
Reputation: 3681
Its not something that could be done with changing type of the list. You might have to create your own reference type which will behave like int
. In .net
structures are't reference types so its impossible with them to get such behaviour like you need.
You have to realize that int
you've added to your list is just copy, so any change done to source won't affect the copy.
Upvotes: 3