C# pass element of value type array by reference

I'd like to pass an element of an array (array contains value type elements, not ref type) by reference.

Is this possible? Thank you

Jon Skeet
people
quotationmark

Yes, that's absolutely possible, in exactly the same way as you pass any other variable by reference:

using System;

class Test
{
    static void Main(string[] args)
    {
        int[] values = new int[10];
        Foo(ref values[0]);
        Console.WriteLine(values[0]); // 10
    }

    static void Foo(ref int x)
    {
        x = 10;
    }
}

This works because arrays are treated as "collections of variables" so values[0] is classified as a variable - you wouldn't be able to do a List<int>, where list[0] would be classified as a value.

people

See more on this question at Stackoverflow