Search code examples
c#javaoperatorsequals-operator

C# what does the == operator do in detail?


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?


Solution

  • As far as I know:

    • it compares value types by value (equality)
    • it compares reference types by reference (identity)
    • except if the == operator is overloaded, then it calls that one.

    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.