3

From the MSDN:

In cases where it is necessary for a value type to behave like an object, a wrapper that makes the value type look like a reference object is allocated on the heap, and the value type's value is copied into it. The wrapper is marked so the system knows that it contains a value type. This process is known as boxing, and the reverse process is known as unboxing. Boxing and unboxing allow any type to be treated as an object.

It seems to me that value types are treated completely different from reference types, even though they inherit from a reference type (both Object and ValueType). Am I right?

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
  • 1
    See: http://stackoverflow.com/a/9841562/414076 . You might find the bit below the second block-quote particularly relevant. – Anthony Pegram Jun 10 '14 at 04:24

1 Answers1

0

By definition, YES.

That is how it is defined by the specifications!

C# has a unified type system. All C# types, including primitive types such as int and double, inherit from a single root object type. Thus, all types share a set of common operations, and values of any type can be stored, transported, and operated upon in a consistent manner. Furthermore, C# supports both user-defined reference types and value types, allowing dynamic allocation of objects as well as in-line storage of lightweight structures.

Are they implemented differently? Yes, but they are still System.Objects.

Anywhere in the specifications, in which they refer to objects or System.Objects, you can be quite certain that it refers to all types.

What would you expect as the output for the following code?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StackOverflowConsole
{
   public class EmptyClass
   {
   }

   public class ReferenceStuff : EmptyClass
   {
      object a;
   }

   public class TypeStuff : EmptyClass
   {
      int a;
   }

   class Test
   {
      static void Main()
      {
         ReferenceStuff r = new ReferenceStuff();
         TypeStuff t = new TypeStuff();

         if (r is EmptyClass)
         {
           Console.WriteLine("r is an EmptyClass");
         }
         if (t is EmptyClass)
         {
            Console.WriteLine("t is an EmptyClass");
         }
      }
   }
}

Not surprisingly, the output is:

r is an EmptyClass
t is an EmptyClass

Why? Because they are both EmptyClass objects. EmptyClass doesn't contribute anything that object doesn't, but both r and t are of type EmptyClass nonetheless.

LVBen
  • 2,041
  • 13
  • 27