I can't find an answer to the following question:
object o = 10; // Box
int i = (int)o; // Unbox
it's clear, but the following isn't clear
bool isInt = o is int; // Is the unbox here or not?
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 common language runtime (CLR) boxes a value type, it wraps the value inside a System. Object instance and stores it on the managed heap. Unboxing extracts the value type from the object.
The process of converting a Reference Type variable into a Value Type variable is known as Unboxing. It is an explicit conversion process.
Boxing is the process of converting a value type to the object type or any interface type implemented by this value type. Boxing is implicit.
Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object.
No, that's not unboxing - it's just checking whether the type is correct. Don't forget that there really is an object involved, with a type. Checking that type is basically the same operation regardless of whether the value is a boxed value type value or not. (There may be some optimizations feasible for value types or any sealed types, as there's no inheritance to consider, but fundamentally it's still checking the "type" part of an object header.)
One way to check that is to compile the code and look at the IL using ILASM:
// object o = 10
IL_0000: ldc.i4.s 10
IL_0002: box [mscorlib]System.Int32
IL_0007: stloc.0
// int i = (int) o;
IL_0008: ldloc.0
IL_0009: unbox.any [mscorlib]System.Int32
IL_000e: stloc.1
// bool isInt = o is int
IL_000f: ldloc.0
IL_0010: isinst [mscorlib]System.Int32
So it uses isinst
- no unboxing is necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With