Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you use String.Equals over ==? [duplicate]

Tags:

string

c#

equals

I recently was introduced to a large codebase and noticed all string comparisons are done using String.Equals() instead of ==

What's the reason for this, do you think?

like image 947
JamesBrownIsDead Avatar asked Nov 02 '09 01:11

JamesBrownIsDead


People also ask

What is the difference between string equals and ==?

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.

What happens when you compare strings with ==?

In String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .

Which is faster equals or ==?

Specifically with regard to strings, yes, == is slightly faster than equals , because the first thing the String.

What would you use to compare two string variables the operator == or the method equals 0?

The String class compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string. Suppose s1 and s2 are two String objects. If: s1 == s2 : The method returns 0.


1 Answers

It's entirely likely that a large portion of the developer base comes from a Java background where using == to compare strings is wrong and doesn't work.

In C# there's no (practical) difference (for strings) as long as they are typed as string.

If they are typed as object or T then see other answers here that talk about generic methods or operator overloading as there you definitely want to use the Equals method.

like image 132
Matthew Scharley Avatar answered Oct 07 '22 00:10

Matthew Scharley