Search code examples
c#value-typeboxing

Does any built-in value type in C# implement any interface?


I'm studying Boxing in C#. And it says if a value type such as a struct implements an interface, there is a boxing operation when we assign an object of type struct to a variable of the type of the interface that has been implemented by the struct.

Now this is my question. Is there any built-in value type such as "int" or "double" that has implemented any interface?


Solution

  • Yes, the standard numeric value types implement quite a few interfaces, namely IEquatable, IComparable and IConvertible. With .NET 7.0, many more where added in preparation for the support of generic math.

    It is correct that if you do something like

    int x = 2;
    IEquatable<int> eq = x;
    if (eq.Equals(3))
    {
        // ...
    }
    

    a boxing conversion is necessary. However, if you write this like

    int x = 2;
    if (x.Equals(3)) 
    // ...
    

    the compiler will typically emit a direct call to the Equals method, avoiding the boxing. And of course, if you simply write if (x == 3) no boxing is involved too, because the compiler directly inserts the instruction for a numeric equality test.