Monday, 26 November 2012

Comparing Strings in c#

Comparing Strings


In comparing two values, the .NET Framework differentiates the concepts of equal-
ity comparison and order comparison. Equality comparison  tests whether  two  in-
stances  are  semantically  the  same; order  comparison  tests which of  two  (if  any)
instances comes first when arranging them in ascending or descending sequence.
Equality comparison  is not a subset of order comparison;  the
two systems have different purposes. It’s legal, for instance, to
have two unequal values in the same ordering position. We re-
sume this topic in “Equality Comparison” on page 245.
For  string  equality  comparison,  you  can  use  the  ==  operator  or  one  of  string’s
Equals methods. The  latter  are more  versatile because  they  allow  you  to  specify
options such as case-insensitivity.
Another difference is that == does not work reliably on strings
if the variables are cast to the object type.


For string order comparison, you can use either the CompareTo instance method or
the static Compare and CompareOrdinal methods: these return a positive or negative
number—or  zero—depending on whether  the  first  value  comes before,  after, or
alongside the second.
Before going into the details of each, we need to examine .NET’s underlying string
comparison algorithms.

No comments:

Post a Comment