Search code examples
c#c#-4.0clrboxing

Curiosity: Converting a C# struct into an object still copies it


This question is more out of curiosity than a real problem. Consider the following code (C# 4.0, if it matters):

class Program {
  static Point myPoint = new Point(3, 5);

  static void Main(string[] args) {
    Console.WriteLine("Point Struct Before: " + myPoint);
    object point = GetPoint();
    Console.WriteLine("Point Object Before: " + point);
    myPoint.X = 10;
    Console.WriteLine("Point Struct After: " + myPoint);
    Console.WriteLine("Point Object After: " + point);
  }

  static object GetPoint() {
    return myPoint;
  }
}

This outputs the following:

Point Struct Before: 3;5
Point Object Before: 3;5
Point Struct After: 10;5
Point Object After: 3;5

Now, this works as it should, meaning the point returned by GetPoint() is being copied rather than referenced. (Otherwise the last line would also have read "10;5".)

My question now is: Why does this work? How does the compiler know whether to copy or reference an object? Does this mean that this decision is done during runtime rather than during compilation?

Also, this now allows me to set point to null whereas structs can't be set to null. Is the struct automatically converted into a nullable type?


Solution

  • You are observing the process called boxing. It essentially converts a value type into a reference type.