For classes, == and != uses object.ReferenceEquals. But for structs, == and != is not defined.
struct S { }
S s1 = new S();
s1 is ValueType; // true
S s2 = new S();
object.Equals(s1, s2); // true
s1 == s2; // operator '==' cannot be applied.
The default behavior for ValueType equals is reflecting over all fields and checking equality, right..? So why isn't == and != defined to just use object.Equals for structs?
Then I took a look at System.Int32 in Mono to see what they did.. Int32 derives from IFormattable, IConvertible, IComparable, IComparable<Int32>, IEquatable<Int32>
, but it does not implement == and !=... But still, == and != can be used on integers as expected.
Is there some compiler magic happening on one of these interfaces or with the built-in valuetypes? Or am I missing something crucial here?
Edit: Btw, could the reason == isn't implemented on structs be for performance reasons? Using reflection to iterate over all the fields might be a bit slow...?