DuxburyDutch
DuxburyDutch

Reputation: 307

Creating a List of reference objects that can be accessed read/write

Here is a simple example of what I want to accomplish in C#:

int v = 5;
ref int vv = ref v;
List<int>ints = new ();
ints.Add(vv);
Console.Write ($"{ints[0]}");   // Prints 5
ints[0] = 6;
Console.Write ($"{ints[0]}");   // Prints 6
Console.Write ($"{v} and {vv}"); // Prints 5 and 5
vv = 7;
Console.Write ($"{v} and {vv}"); // Prints 7 and 7

So the change in ints[0] is not passed on to either v or vv. I would say that adding the reference vv to the List<> will put an actual reference in the list. I've tried List<ref int> ints, but the compiler does not accepts this.
In a previous C++ version of the software I simply used pointers (&v and *v), but I prefer to avoid unsafe code. I wonder if there is a straightforward safe way to accomplish modifying v and vv directly through ints[0].

Upvotes: -1

Views: 45

Answers (0)

Related Questions