Laxes
Laxes

Reputation: 53

C# 7.3+ ref variable intended behaviour?

I just came across a situation that boils down to this:

        private static uint[] intArray;

        private static void Main(string[] args)
        {
            intArray = new uint[10];

            for(var i = 0u; i < intArray.Length; i++)
            {
                intArray[i] = i;
            }

            ref var value = ref intArray[4];

            Array.Resize(ref intArray, 100);

            value += 10; // what are we modifying here? The old memory?

            Console.WriteLine(intArray[4]); // prints 4 not 14 because the array is resized
        }

Is this the intended behavior for ref variables in C#?

Upvotes: 5

Views: 180

Answers (1)

iakobski
iakobski

Reputation: 1274

Yes, this is expected. Array.Resize() does not literally resize the array, it can't, an array is contiguous memory. What it does is create a new array with the required size and copy the values from the old array into it. As explained here: https://learn.microsoft.com/en-us/dotnet/api/system.array.resize?view=netframework-4.8

You also have the question in the comment: "what are we modifying here? The old memory?" Yes, although you have no way of accessing the old array, there is still your reference to the element within it, so the GC cannot delete it until value goes out of scope. So there is no error from updating the contents.

int is a value type, so the value is copied to the new array. If you had an array of Object the value of the reference would be copied and you could still access that through your variable value.

Upvotes: 4

Related Questions