C
C#ā€¢16mo ago
ubuntu-user

ā” struct inheriting from IEquatable<T>

hi, what is the point for a struct to inherit from IEquatable<T> ? šŸ¤” have a nice day !
4 Replies
Jimmacle
Jimmacleā€¢16mo ago
the same reason you would for any other type, to define a custom equality implementation also, types don't inherit interfaces, they implement them
canton7
canton7ā€¢16mo ago
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.
Thinker
Thinkerā€¢16mo ago
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.
Accord
Accordā€¢16mo ago
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.
Want results from more Discord servers?
Add your server
More Posts