10

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

1
  • you can pass the array element using ref keyword. Commented Mar 17, 2015 at 19:34

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

Comments

9

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.