I had a question on a quiz that asked "What is the following doing?":
// Value is an int
IComparable thing = (IComparable)value;
Apparently the answer is boxing, but I don't know why. Why is this considered boxing and what is it doing? I was under the impression that boxing can only happen with object
.
Why is this considered boxing
Because you're converting a value type into a reference type by creating an object (the "box") containing the value. It's boxing in the same way that you're used to with object
.
what is it doing
Boxing, but with a result type of IComparable
.
I was under the impression that boxing can only happen with object.
No, boxing can happen with any reference type that is in the value type's inheritance hierarchy. In reality, this means:
object
ValueType
Enum
(for enums)