CSharp - Method ref modifier

Introduction

To pass by reference, C# provides the ref parameter modifier.

A parameter can be passed by reference or by value, regardless of whether the parameter is a reference type or a value type.

In the following example, p and x refer to the same memory locations:

Demo

using System;
class MainClass/* w  ww .j  av  a2  s  .  co m*/
{
       static void Test (ref int p)
       {
         p = p + 1;               // Increment p by 1
         Console.WriteLine (p);   // Write p to screen
       }

       static void Main()
       {
         int x = 8;
         Test (ref  x);            // x
         Console.WriteLine (x);   // x is now 9
       }
}

Result

assigning p a new value changes the contents of x.

ref modifier is required both when writing and when calling the method.

Related Topics

Quiz