C# language feature:

  • Ref returns and locals

applies to

  • method return values

benefit

  • Allows passing and return of references from methods. Can be used to improve performance when working with large data structures.

how to use

  • Prefix parameter and or return value type with ref modifier.

note

  • ref must be mutable fields or passed by reference, also ref can be used to reference arrays elements.

example:

        ref int Get_Larger_Reference(ref int number1, ref int number2)
        {
            if (number2 > number1)
                return ref number2;
            return ref number1;
        }

        void Use_of_Ref_Example()
        {
            int a = 5, b = 8;
            int c = Get_Larger_Reference(ref a, ref b);
            c = 9;
            System.Console.WriteLine($"{a} {b} {c}"); // 5 9 9
        }