Quoting from the MSDN Link for ValueType Class
In cases where it is necessary for a value type to behave like an object, a wrapper that makes the value type look like a reference object is allocated on the heap, and the value type's value is copied into it. The wrapper is marked so the system knows that it contains a value type.
This means when I code like "integerVariable.ToString();" a wrapper-object created allows using this method and similarly all the other methods of System.Object.
Is this understanding correct?
How are these objects different from the 'regular' objects?
Is the Garbage Collection different for such object? If yes, how?
Thanks in advance.
The wrapper is a "box"; re garbage collection of boxes - there is no difference as far as the grabage collector is concerned. A box is collected with exactly the same rules and treatment as any other object.
however, if a value-type overrides a method (such as
ToString()
), it is not necessary to box it to call the method. Hence, value-types should (as a matter of routine) override as many of theobject
methods as possible ;-pYou can see the difference in the IL (via reflector) - so for the C#:
We have the IL:
Note that
ToString()
doesn't involve a box, butGetType()
does atL_0007
(since it isn't (can't be) overridden)Yes that understanding is correct.
These objects are no different from 'regular' objects in the CLR.
Since these objects (also called 'boxes' becuase they wrap value types) are just like any other object the garbage collector is the same too.