Is == shortcut to Equal () method?

Possible duplicate:
What is the difference between ".equals and =="

In Java langage, I think when you do comparaison as Object1 == Object2; By default, it compares the hashcode of an object. Unless you rewrite the equal () method because the comparator == is a kind of shortcut for the equal method. Please correct me if I am wrong! Because I'm pretty new to Java.

The question is, is it the same in C #? Thanks for answers..

+4
source share
5 answers

In C #, == never directly calls x.Equals(y) (except, perhaps if you included string.Equals(x,y) ):

  • for some built-in types a direct comparison is performed ( int , etc. have an opcode)
  • if an explicit == operator is defined, which is called
  • for Nullable<T> "canceled" rules apply, then == applies to values โ€‹โ€‹if both values โ€‹โ€‹are not equal to zero.
  • for classes, referential equality is used by default
  • for structs there is no implementation == by default
+8
source

By default, the operator == == // "> checks the reference equality to determine if two references point to the same object, therefore, to get this functionality, the reference types do not need to implement operator ==. When the type is immutable, that is, data contained in the instance cannot be changed, overloading the == operator to compare the equality of values โ€‹โ€‹instead of reference equality can be useful, since they can be considered the same as immutable objects if they have the same value. ATOR == in immutable types is not recommended.

Equals is a virtual method that allows any class to override its implementation. Any class that represents a value, essentially any type of value or a group of values, such as a complex number class, must override Equals. If the type implements IComparable, it must override Equals.

+3
source

When you compare objects with ==, it compares the links (they point to the same object). == most definitely is not a shortcut to equals.

In C #, == does the same with one important difference - in C # you can overload ==, so you can define a new value for the operator. For example, line == compares the contents of a line with another.

+2
source

In Java, as well as in C #, the == operator is used to compare references, while the Equals () method compares values.

+1
source

No, this is not the same. obj1 == obj2 is true if both links point to the same object. But, for example, if these are two different string objects that contain the same content, it will be false.

Example:

 object obj1 = new Something(123); object obj2 = new Something(123); => obj1 != obj2 
0
source

Source: https://habr.com/ru/post/1340754/


All Articles