Manus
Manus

Reputation: 113

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

Upvotes: 10

Views: 8766

Answers (2)

Adam Diament
Adam Diament

Reputation: 4840

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://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/ref-returns

Upvotes: 8

Jon Skeet
Jon Skeet

Reputation: 1500185

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.

Upvotes: 19

Related Questions