views:

69

answers:

2

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...?

+2  A: 

ValueTypes should be boxed in order to be used as (how you call them) types aka objets. Boxing is a performance penalty, yes.

yatagarasu
+1  A: 

Comparison for System.Int32 are defined in the C# norm in 14.9.1 Integer comparison operators and are mapped directly to the IL opcodes like OpCode.Ceq for equality in the C# compiler so they aren't defined as standard operators on the System.Int32 type directly.

So yes compiler magic it is.

VirtualBlackFox