Sobes.tech
Junior — Senior

Boxing and unboxing of values in C#

livecode

Task condition

In the function Example2, the following occurs:

  • An object obj is created, which encapsulates the integer value 5.
  • Then, the value is extracted (unboxed) from obj and stored in the variable num of type int.
  • The variable num is assigned a new value of 12.
  • After that, the contents of obj and the current value of num are printed to the console.

Question: what exactly will be printed and what is their explanation?

static void Example2()
{
    object obj = 5;
    int num = (int)obj;
    num = 12;

    Console.WriteLine(obj);
    Console.WriteLine(num);
}