in c# what does exactly happen in the background when you do a comparison with the "==" operator on two objects? does it just compare the addresses? or does it something like Equals() or CompareTo() ?
PS: what about the "==" operator in java? does it behave the same?
From MSDN:
No ... the == operator does not always behave the same in java and in c#.
For example with Strings; Java == does compare the references of the string objects... (if you use primitve types, == in java compares the values). That's why
will not return true in java...
In C# in contrast, the == operator does behave different on strings. For example, it will return true in the following case:
The behavior of == operator depends how the variable you are applying it to was declared (not on the class of the object, I'll add an example).
For value types it will compare their values.
For reference types a == b returns true if a is the same object as b, unless the == operator was overloaded. Not overridden as others said, you can't override operators in c# because they are not virtual.
object obj_a, obj_b; string str_a, str_b;
The output of that program is
As far as I know:
Equals is implemented in object and can be overridden as well. The default implementation in Object performs a reference comparison for reference types. So by default, Equals and == do the same.
I think in java you cannot overload the == operator. But my Java knowledge is pretty outdated.
Edit: Note that the
==
operator is a static method. It is bound at compile time, base on the types of your variables or fields.Equals
is a virtual method that is found at runtime, based on actual runtime types.As an extension to Stefan's excellent answer - another exception is if the operands involve
Nullable<T>
- in which case "lifted" operators apply (14.2.7 in ECMA 334v4):What that means is: because there is an equality operator between (say):
Thus there is an implicit operator of the form (although done differently):
What it does depends on the context.
http://en.csharp-online.net/ECMA-334:_14.9_Relational_and_type-testing_operators