-3

Been using C# for a while and I've been thinking this:

public static void Main(Strings[] args){
    ...
    Person p = new Person("Bob",23,"Male");
    List<Object> al = new List<Object>();
    al.Add(p);
    Person p = (Person)al[0];
}

A typical example of boxing and unboxing in Collection, but question is: when boxing the variable, the CLR allocates a extra space in GC heap and treat p as object, yet the Person class is "larger" than System.Object

So according to that, that may lose some values that Person class owns additionally, it will fail to get some data after unboxing.

How CLR work that out?

Any solutions are welcomed

LifeScript
  • 1,116
  • 5
  • 15
  • 24
  • 9
    There is no boxing/unboxing here. **Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type**. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. **Unboxing extracts the value type from the object.** from [MSDN](http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx) – Habib Aug 22 '13 at 15:34
  • How can Person *loose* values? We are in the managed environment and we can't just iterpret the random block of memory as one type or another. – alex Aug 22 '13 at 15:35
  • 1
    Maybe helpfull to read [this](http://stackoverflow.com/questions/2111857/why-do-we-need-boxing-and-unboxing-in-c) and [this](http://stackoverflow.com/questions/1085144/what-is-the-difference-between-boxing-unboxing-and-type-casting) – rene Aug 22 '13 at 15:43

2 Answers2

2

Person is a class, so used by reference. No boxing or unboxing.

As opposed to a value type that may require boxing.

Philippe Lignon
  • 403
  • 4
  • 10
0

If the Person type is really a structure, what you haven't declared explicitly, the space on the heap is surely larger than the space needed for an object of System.Object class. However, at the moment when the data are moved to heap, the object itself is not the value you are giving to the Add method, this value is only a reference to the boxed object. If System.Object was a structure, then yes, the data will have to be truncated to fit the size of the structure. This is the reason why inherited structures aren't allowed.

IS4
  • 11,945
  • 2
  • 47
  • 86