0

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?

Magnus
  • 45,362
  • 8
  • 80
  • 118
HosseinSedghian
  • 383
  • 2
  • 15
  • 1
    Where did you get that statement from? IMHO, boxing and unboxing is not related to interfaces. It happens without interfaces. – Thomas Weller Apr 17 '23 at 06:47
  • 11
    Look at [the docs](https://learn.microsoft.com/en-us/dotnet/api/system.int32) for `int` - it implements a whole bunch of interfaces – Hans Kesting Apr 17 '23 at 06:50
  • 1
    The whole [generic math](https://learn.microsoft.com/en-us/dotnet/standard/generics/math) feature is based on interfaces, with generic methods used to avoid the boxing problem. In general, structs are usually used for memory/performance reasons, and then you usually want to avoid interfaces anyway, or only use them for generic constraints. – JonasH Apr 17 '23 at 06:56
  • 1
    related: https://stackoverflow.com/questions/63671/is-it-safe-for-structs-to-implement-interfaces – Tim Schmelter Apr 17 '23 at 06:59
  • They pretty much all do, which you could see for yourself by reading the relevant documentation. You should ALWAYS read the relevant documentation before posting a question here. – jmcilhinney Apr 17 '23 at 09:16

1 Answers1

2

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.

PMF
  • 14,535
  • 3
  • 23
  • 49