Alex Rivera | Logout

Using == or Equals for string comparison

Asked 2009-12-28T10:10:04.157
12

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?

Edit
Report

1 Answer

1

Best-practise-wise, I would tend to always use an Equals() function for string comparison. This makes it clear when someone else reads your code that you specifically want the strings compared.

answered 2009-12-28T10:17:49.813

Your Answer