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?
Yes, the standard numeric value types implement quite a few interfaces, namely
IEquatable,IComparableandIConvertible. 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
a boxing conversion is necessary. However, if you write this like
the compiler will typically emit a direct call to the
Equalsmethod, avoiding the boxing. And of course, if you simply writeif (x == 3)no boxing is involved too, because the compiler directly inserts the instruction for a numeric equality test.