CSharp - What is the output: Implications of passing by reference?

Question

What is the output of the following code?

using System;
class MainClass
{
       static int x;

       static void Main() { Test (out x); }

       static void Test (out int y)
       {
           Console.WriteLine (x);               
           y = 1;                               
           Console.WriteLine (x);               
       }
}


Click to view the answer

0
1

Note

When you pass an argument by reference, you alias the storage location of an existing variable.

In the code, the variables x and y represent the same instance.

Demo

using System;
class MainClass//from w  w  w  .  j ava 2  s.  c  o m
{
       static int x;

       static void Main() { Test (out x); }

       static void Test (out int y)
       {
           Console.WriteLine (x);               
           y = 1;                               
           Console.WriteLine (x);               
       }
}

Result

Related Quiz