Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison in .NET

What is the difference (in bref) between (.NET)

myString == otherString

and

myString.CompareTo(otherString) == 0
like image 728
serhio Avatar asked May 14 '26 19:05

serhio


1 Answers

There's no difference, except when myString is null, in which case myString.CompareTo(otherString) throws an error (NullReferenceException). Also, using CompareTo is a little bit slower than ==.

Only use CompareTo when you are interested in knowing if a string is before or after another one in an alphabetical sorting of them. For example "Car".CompareTo("Cat") returns -1 because "Car" is before "Cat" when ordered alphabetically.

like image 147
Diego Avatar answered May 16 '26 09:05

Diego