๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

C# Ref Locals and Returns

A ref variable aliases another variable instead of copying its value. Writing through the alias writes the original storage directly.

A ref local aliases a variable

The alias and the score are the same storage. Writing 9 through the alias changes the score.

using System;

class Program
{
    static void Main(string[] args)
    {
        int score = 5;
        ref int alias = ref score;
        alias = 9;
        Console.WriteLine(score);
    }
}

A ref return into an array

Find returns a ref to one array element. The caller writes 70 through that ref, straight into the array.

using System;

class Program
{
    static ref int Find(int[] data, int index)
    {
        return ref data[index];
    }

    static void Main(string[] args)
    {
        int[] data = { 10, 20, 30 };
        ref int slot = ref Find(data, 1);
        slot = 70;
        Console.WriteLine(data[1]);
    }
}

A ref parameter writes the caller variable

Bump receives the count itself, not a copy. Its increment lands in the caller variable.

using System;

class Program
{
    static void Bump(ref int value)
    {
        value = value + 1;
    }

    static void Main(string[] args)
    {
        int count = 5;
        Bump(ref count);
        Console.WriteLine(count);
    }
}

Example

using System;

class Program
{
    static void Swap(ref int a, ref int b)
    {
        int temp = a;
        a = b;
        b = temp;
    }

    static void Main(string[] args)
    {
        int x = 3;
        int y = 8;
        Swap(ref x, ref y);
        Console.WriteLine(x);
        Console.WriteLine(y);
    }
}

Key points

  • A ref local is declared with ref on both sides of the assignment.
  • Assigning through a ref local changes the variable it aliases.
  • A method can return a ref to storage owned by the caller, such as an array element.
  • A caller stores a ref return in a ref local to keep write access to that storage.
  • A ref parameter lets a method write the caller variable passed to it.
  • Each ref call site repeats the ref keyword, so the sharing stays visible in the code.

In this example, Swap receives both variables by ref. The assignments inside Swap write the caller variables directly. The prints show the pair exchanged, 8 then 3.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A ref local alias points at score. What happens when `alias = 9;` runs?