C# in Depth

Cover of C# in Depth
Order now (3rd edition)

Boxing copies values

Chapter 2: Core foundations: building on C# 1: 2.3.4

Created: 4/4/2008
Last updated: 5/7/2008

One point I didn't mention when discussing boxing was that the process of boxing always copies a value. The newly created box doesn't know about the variable (or other expression) that was used to create it - it just knows about the value. So, for example:

int x = 5;
object boxed = x; // A copy of the value 5 is boxed
x = 10; // This doesn't change the value in the box
Console.WriteLine(boxed); // So this prints 5