Search code examples
c#listmutable

List that always holds current variables value. C#


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.


Solution

  • 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.