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/*w  ww . ja  v a  2 s  .  co m*/
{
   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