Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# pass element of value type array by reference

Tags:

c#

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

like image 650
Manus Avatar asked Mar 17 '15 19:03

Manus


2 Answers

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.

like image 184
Jon Skeet Avatar answered Oct 11 '22 22:10

Jon Skeet


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

like image 5
Adam Diament Avatar answered Oct 11 '22 22:10

Adam Diament