Possible Duplicate:
C#: Are string.Equals() and == operator really same?
For string comparison, which approach is better (and safe):
string s1="Sarfaraz";
string s2="Nawaz";
bool result1 = (s1==s2) ;//approach 1
bool result2 = s1.Equals(s2) ;//approach 2
Or both are same under the hood?
The main difference between the . equals() method and == operator is that one is a method, and the other is the operator. We can use == operators for reference comparison (address comparison) and . equals() method for content comparison.
In java both == and equals() method is used to check the equality of two variables or objects. == is a relational operator which checks if the values of two operands are equal or not, if yes then condition becomes true. equals() is a method available in Object class and is used to compare objects for equality.
== is a reference comparison, i.e. both objects point to the same memory location. . equals() evaluates to the comparison of values in the objects.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
I like Equals()
because the available StringComparison
option is very useful.
The ==
and !=
operators are based on the value, so they are safe to use, even though String
is a reference type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With