Why Can I Cast an Int to IComparable?

Viewed 517

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.

3 Answers

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:

  • Any interface the value type supports
  • object
  • ValueType
  • Enum (for enums)

Because int (that alias of Int32) implements IComparable.

namespace System
{
    //
    // Summary:
    //     Represents a 32-bit signed integer.
    public readonly struct Int32 : IComparable, IComparable<Int32>, IConvertible, IEquatable<Int32>, IFormattable
    {
    .
    .
    .
    }
.
.
.
}

IComparable is a reference type, Int32 is a value type. So when you cast Int32 to IComparable, boxing happened.

Related