In C++, I can do something like this:
int i[10] = new int[10];
int *p = &i[5];
Then, I can always know that p points to the 5th element of int array i, regardless of i‘s contents.
Is there any way to do something similar in C#?
I realize this is likely one of the ways in which C# "protects" us from ourselves, so I’m not looking for an exact equivalent, but rather a similar concept… that is, being able to refer to the contents of some other variable, rather than the instance of the variable itself.
Here’s my use case I’m thinking of. I have an array of strings. I would like to have another array of references to those array elements. Something like this (obviously not valid code):
string[] s = new string[] { "one", "two", "three", "four", "five", "six" };
stringref[] sr = new stringref[] { &s[0], &s[1], &s[2], &s[3], &s[4], &s[5] };
Console.WriteLine(sr[1]); // == "two"
s[1] = "two point zero";
Console.WriteLine(sr[1]); // == "two point zero"
Certainly, ref parameters do this, and out parameters allow you to write to a specific variable. But what about non-parameters? Can you store a ref? Can you keep an array of refs or a dictionary?
It seems like if the ability to do it with parameters is present, there should be a way to do it without them.
No. Putting
unsafecode aside, which does allow holding pointers to memory locations, there’s no way to store a reference to a variable in C#.refandoutarguments provide the only means to take a reference but you can’t save them anywhere.You can workaround this limitation by wrapping fields in a
classand using its reference instead. This is what the compiler does to capture variables in closures:For instance, when you write:
In the second line, the compiler will have to take out the anonymous method and store it as a separate method in the class. Obviously, that method won’t have access to
integervariable. It somehow needs to pass a “reference” tointegervariable to that anonymous method. Since it’s not possible, it’ll generate aclasswith a field to hold an integer and uses an instance of that class to store the variable. Basically, the local variable is promoted to a field in a class and is stored in the heap.