Use the Compare and CompareOrdinal methods on strings. See the results of CompareTo.
Compare. This method determines the sort order of strings. It checks if one string is ordered before another when in alphabetical order, whether it is ordered after, or is equivalent.StringsString Equals
Method info. There are 3 methods that provide this functionality—Compare, CompareOrdinal and CompareTo. Two strings are always compared.
An example. Normally we need the Compare methods for sorting algorithms. We use them to test whether one string comes before or after the other in a plain ASCII sort.Sort
Part A: We use the string.Compare static method. It is not called on an instance, and we must pass 2 arguments.
Part B: We invoke the static CompareOrdinal—this treats strings by their numeric (ordinal) character values.
Part C: We call the CompareTo instance method. We cannot use this method on a null variable.
Result: If the first string is bigger, the result is 1. If the first string is smaller, the result is -1.
And: If both strings are equal, the result is 0. The number essentially indicates how much "larger" the first string is.
C# program that uses Compare, CompareOrdinal and CompareTo methods
static void Main()
string a = "a";
string b = "b";
// Part A: use static Compare.
int c = string.Compare(a, b);
// Part B: use static CompareOrdinal.
c = string.CompareOrdinal(b, a);
// Part C: use CompareTo.
c = a.CompareTo(b);
c = b.CompareTo(a);
-1 (This means a is smaller than b)
1 (This means b is smaller than a)
Review, results. It is important to understand the possible results of Compare methods. Here are the int return values—we see just 3 values: -1, zero, and 1.Int, uint