CSharp - Method ref Locals

Introduction

You can define a local variable that references an element in an array or field in an object:

int[] numbers = { 0, 1, 2, 3, 4 };
ref int numRef = ref numbers [2];

numRef is a reference to the numbers[2]. When we modify numRef, we modify the array element:

numRef = 100;
Console.WriteLine (numRef);        // 100
Console.WriteLine (numbers [2]);   // 100

The target for a ref local must be an array element, field, or local variable.

The target for a ref local cannot be a property.

Demo

using System;
class MainClass//from   w w w . j  a  v a2  s.  com
{
   public static void Main(string[] args)
   {
        int[] numbers = { 0, 1, 2, 3, 4 };
        ref int numRef = ref numbers [2];
        
        numRef = 100;
        Console.WriteLine (numRef);        // 100
        Console.WriteLine (numbers [2]);   // 100

   }
}

Result