4

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 Answers3

8

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)
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Boxing happens when you "box" (or, simply, cast) a value to an object type.

The most common example is about casting a value to object:

var num = 5; //Integer value
var boxed = (object)num; //object

But anything on the inheritance chain or implemented interfaces works and Int32 implements IComparable: https://learn.microsoft.com/en-us/dotnet/api/system.int32?view=netframework-4.8

Alvin Sartor
  • 2,249
  • 4
  • 20
  • 36
-1

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.

player2135
  • 111
  • 4