CSharp - What is the output: Value Copying semantics of boxing and unboxing?

Question

What is the output from the following code

int i = 3;
object boxed = i;
i = 5;
Console.WriteLine (boxed);    


Click to view the answer

3

Note

Boxing copies the value-type instance into the new created object.

Unboxing copies the contents of the object to a value-type instance.

In the code above, changing the value of i doesn't change its previously boxed copy:

Demo

using System;
class MainClass/*from  w w  w . ja  va  2 s.  c  o m*/
{
   public static void Main(string[] args)
   {
      int i = 3;
      object boxed = i;
      i = 5;
      Console.WriteLine (boxed);    // 3
   }
}

Result

Related Topic