Comparing structs for equality without boxing
Let me add that for struct
s, if you do not define comparations, the details get complicated.
For example How to define value equality for a type says:
Any struct that you define already has a default implementation of value equality that it inherits from the System.ValueType override of the Object.Equals(Object) method. This implementation uses reflection to examine all the fields and properties in the type. Although this implementation produces correct results, it is relatively slow compared to a custom implementation that you write specifically for the type.
See also Performance implications of default struct equality in C# for more details, including:
There is an optimized default version for Equals and GetHashCode but you should never rely on it because you may stop hitting it with an innocent code change.
- The first of the following methods is illegal since structs do not implicitly override the equality operators ==/!=.
True.
- The second "appears" to avoid boxing.
The signature of the called method is EqualityComparer<T>.Equals(T,T)
which uses the type T
for the parameters, so it does not require boxing to call.
The implementation of the default comparer checks if T
is IEquatable<T>
and if so uses a comparer that uses IEquatable<T>.Equals
and else uses a comparer for Object.Equals
, so internally there might be boxing applied if the struct is not IEquatable
('only if needed').
- The third method should always box the struct since it's calling object.Equals(object o).
True.
- The fourth has both overloads available (object/T) so I'm assuming it will avoid boxing as well. However, the target struct would need to implement the IEquatable interface, making the helper extension method not very helpful.
Yes, it does not require boxing, as per this SO answer. This is the effective code you get for the specific case of T : IEquatable
from the EqualityComparer<T>.Default
.