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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With