I am using C#. When I am comparing two char value its sending me correct output, like,
'-'.CompareTo('!') //Its sending me positive value 12
means '-' > '!' is true
But when I am comparing two string of same value its sending me different result
"-".CompareTo("!") //Its sending me negative value -1
means "-" > "!" is false
Can anyone please explain me why it is doing so ? Should not it be 'true' for both cases ?
Unicode is the universal character encoding used to process, store and facilitate the interchange of text data in any language while ASCII is used for the representation of text such as symbols, letters, digits, etc. in computers. It is a character encoding standard for electronic communication.
When two separate string instances contain the exact same sequence of characters, the values of the strings are equal, but the references are different. As described in Section 7.9.6, the reference type equality operators can be used to compare string references instead of string values. Not the answer you're looking for?
The string equality operators compare string values rather than string references. When two separate string instances contain the exact same sequence of characters, the values of the strings are equal, but the references are different.
string.Compare Compares two specified String objects and returns an integer that indicates their relative position in the sort order.
String's Compare method is culture specific. That's why you get different results. use string.CompareOrdinal
instead, which is byte by byte comparison.
var v = '-'.CompareTo('!');//12
var s = string.CompareOrdinal("-", "!");//12
Best Practices for Using Strings in the .NET Framework
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