Pregunta

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

¿Fue útil?

Solución

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

As opposed to a value type that may require boxing.

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top