Question

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

Was it helpful?

Solution

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

As opposed to a value type that may require boxing.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top