Marcos Alfonso
Marcos Alfonso

Reputation: 139

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.

Upvotes: 0

Views: 220

Answers (4)

Setyo N
Setyo N

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

Tobbe
Tobbe

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

Artem Koshelev
Artem Koshelev

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

Piotr Auguscik
Piotr Auguscik

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

Related Questions