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?
I wouldn’t use:
unless I knew
aacouldn’t possibly be null. I might use:But I’d mainly use that it I wanted to use one of the specific
StringComparisonmodes (invariant, ordinal, case-insensitive, etc). Although I might also use theStringComparerimplementations, since they are a bit easier to abstract (for example, to pass into aDictionary<string, Foo>for a case-insensitive ordinal dictionary). For general purpose usage,is fine.