Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using == or Equals for string comparison

In some languages (e.g. C++) you can't use operators like == for string comparisons as that would compare the address of the string object, and not the string itself. However, in C# you can use == to compare strings, and it will actually compare the content of the strings. But there are also string functions to handle such comparisons, so my question is; should you?

Given two strings:

string aa = "aa"; 
string bb = "bb";

Should you compare them like this:

bool areEqual = (aa == bb); 

Or should you use the Equal function, like this:

bool areEqual = aa.Equals(bb); 

Is there any technical difference anyway? Or reasonable arguments for best practice?

like image 298
stiank81 Avatar asked Dec 28 '09 10:12

stiank81


People also ask

Can we use == for string comparison?

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.

What happens if you use == for strings?

String Comparison With Objects Class The method returns true if two Strings are equal by first comparing them using their address i.e “==”. Consequently, if both arguments are null, it returns true and if exactly one argument is null, it returns false.

Which is better == or equals?

equals() method. The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.

How do you compare two strings equal?

The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.


1 Answers

I wouldn't use:

aa.Equals(bb)

unless I knew aa couldn't possibly be null. I might use:

string.Equals(aa,bb)

But I'd mainly use that it I wanted to use one of the specific StringComparison modes (invariant, ordinal, case-insensitive, etc). Although I might also use the StringComparer implementations, since they are a bit easier to abstract (for example, to pass into a Dictionary<string, Foo> for a case-insensitive ordinal dictionary). For general purpose usage,

a == b

is fine.

like image 160
Marc Gravell Avatar answered Oct 20 '22 03:10

Marc Gravell