C# pass element of value type array by reference

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.


As an addition to Jon's answer, from C# 7 you can now do this kind of thing inline without the need for a wrapping method, with a "ref local". Note the need for the double usage of the "ref" keyword in the syntax.

 static void Main(string[] args)
    {
        int[] values = new int[10];
        ref var localRef = ref values[0];
        localRef = 10;
        //... other stuff
        localRef = 20;

        Console.WriteLine(values[0]); // 20
    }

This can be useful for situations where you need to refer to or update the same position in an array many times in a single method. It helps me to to avoid typos, and naming the variable stops me forgetting what array[x] refers to.

Links: https://www.c-sharpcorner.com/article/working-with-ref-returns-and-ref-local-in-c-sharp-7-0/ https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/ref-returns

Tags:

C#