Skip to content

Conditional ref expressions C# 7.2code reduction

Use the conditional operator with ref returns and ref locals.

C# 7.0 introduced ref return C# 7.0 and ref local C# 7.0, allowing methods to return references to variables. However, the conditional operator ?: didn't support ref expressions, limiting the ability to conditionally select between references.

C# 7.2 extends the conditional operator to work with ref expressions, allowing you to conditionally choose between two references without copying values.

Code

C#
ref int GetReference(int[] array, bool useFirst)
{
    return ref (useFirst ? ref array[0] : ref array[^1]);
}

int[] numbers = { 10, 20, 30 };
ref int value = ref GetReference(numbers, true);
value = 100;  // numbers[0] is now 100
C#
ref int GetReference(int[] array, bool useFirst)
{
    if (useFirst)
        return ref array[0];
    else
        return ref array[^1];
}

int[] numbers = { 10, 20, 30 };
ref int value = ref GetReference(numbers, true);
value = 100;  // numbers[0] is now 100

Notes

  • Both branches of the conditional expression must be ref expressions
  • The ref keyword must appear before both the conditional operator and each branch
  • This works with ref readonly as well for read-only references
  • All expressions must return compatible ref types

More information