DEV Community

Juarez Júnior
Juarez Júnior

Posted on

C# Tip: Ref Locals and Returns

Let’s talk about Ref Locals and Returns, introduced in C# 7, which allow methods to return references to variables, enabling direct manipulation of the original value. See the example in the code below.

using System;

public class Program
{
    public static void Main()
    {
        int[] numbers = { 10, 20, 30 };

        // Get a reference to the second array element and modify its value
        ref int reference = ref GetReference(numbers, 1);
        reference = 50;

        Console.WriteLine(string.Join(", ", numbers)); // Output: 10, 50, 30
    }

    public static ref int GetReference(int[] array, int index)
    {
        return ref array[index]; // Returns the reference to the array element
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:
With Ref Locals and Returns, you can return references to variables instead of their values. This allows you to manipulate the original variable directly, without creating copies. In the example above, we show how to return and modify a reference to an array element directly.

I hope this tip helps you understand how to use Ref Locals and Returns to manipulate data directly and efficiently! Until next time.

Top comments (0)