ā struct inheriting from IEquatable<T>
hi, what is the point for a struct to inherit from IEquatable<T> ?
š¤
have a nice day !
4 Replies
the same reason you would for any other type, to define a custom equality implementation
also, types don't inherit interfaces, they implement them
IEquatable<T>
is a slightly odd one.
Every object has a bool Equals(object)
method which will tell you whether it's equal to another object. Structs have one too. So what's the point of adding a bool Equals(T)
method as well?
The issue is that Equals(object)
takes an object
, and in order turn a struct into an object
you need to box it, which means an allocation on the heap. Most of the time when you're using a struct you're trying to avoid too many heap allocations.
If the struct implements Equals(T)
it means you can call it without boxing an instance of the struct, which avoids the issue.
So it's good practice to implement IEquatable<T>
for your structs (or create a record struct
which implements it for you). Some people also implement it for classes, but since turning an instance of a class into object
is very cheap, there's no technical reason to.It's also a very explicitly statement of intent. Every type has an
Equals
method by default, but there's no indication of whether the method is actually overwritten or not. When you implement IEquatable<T>
, you're communicating explicitly that yes, this type supports value equality. Otherwise you could very possibly end up with annoying bugs or performance issues because the type doesn't actually support what you think it does.Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.