If I write
int i=100;
then does it get stored as int
in memory taking 4 Bytes or stored as object
, and at the time of it's retrieval unboxing concept used (int extracted from object class type object).
If I write
int i=100;
then does it get stored as int
in memory taking 4 Bytes or stored as object
, and at the time of it's retrieval unboxing concept used (int extracted from object class type object).
No there is no boxing going in your example the int only takes 4 bytes. Boxing only occurs when manually storing a value type in an object
variable.
int i = 100; // No boxing
i = i + 1; // No boxing
object o = i; // Boxing
int j = (int)o; // Unboxing
The simplest way to understand boxing is to understand some details how value types and reference types are handled in the CLI/CLR (the layer of framework that executes the output from a C# or other .net compiler). In particular, one needs to recognize that for every value type the Framework also defines a corresponding sealed reference type which derives from class System.ValueType
(which in turn inherits from System.Object
) and has the same public and private fields as the original value type(*). Storage locations of value type always hold value types, while storage locations of reference types always hold reference types. No exceptions. If an attempt is made to use a value type in a situation that requires a reference type, the system will create a new instance of the reference type corresponding to that value type, copy the public and private fields from the value to be stored, and then use that new instance. This is called "boxing".
Note that while C# pretends that all value types inherit from System.Object
, such a statement relies upon a loose definition of "inheritance" which can be more confusing than useful. If one defines the statement "X
inherits Y
" to mean "instances of X
can be implicitly used as instances of Y
", then unboxed value types do not inherit Object
, but their values can be copied into instances of boxed value types which do.