Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison : operator==() vs. Equals() [duplicate]

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?

like image 586
Nawaz Avatar asked Jan 19 '11 19:01

Nawaz


People also ask

What is the difference between Equals () and == operator?

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.

When would you use == vs equal () and what is the difference?

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.

What is difference between == and Equals method of string class?

== is a reference comparison, i.e. both objects point to the same memory location. . equals() evaluates to the comparison of values in the objects.

Can you compare strings with ==?

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.


1 Answers

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.

like image 141
CaptainPlanet Avatar answered Sep 30 '22 01:09

CaptainPlanet