Understanding C#'s `String.CompareOrdinal()` Method: Culture-Insensitive String Comparison

Learn how to use C#'s `String.CompareOrdinal()` method for culture-insensitive and case-sensitive string comparisons. This tutorial explains its functionality, demonstrates its use with various string inputs, and highlights its advantages in scenarios requiring precise Unicode-based string comparisons.



Understanding C#'s `CompareOrdinal()` Method

The C# `String.CompareOrdinal()` method compares two strings based on their character's Unicode values. Unlike other comparison methods, it ignores culture-specific rules and case sensitivity, providing a straightforward numerical comparison.

How `CompareOrdinal()` Works

The method compares the strings character by character using their Unicode values. The result indicates the relative order of the strings:

  • 0: The strings are equal.
  • Positive Number: The first string is lexicographically greater than the second string (comes later in alphabetical order).
  • Negative Number: The first string is lexicographically less than the second string (comes earlier in alphabetical order).

The magnitude of the positive or negative number represents the difference between the first differing characters' Unicode values.

`CompareOrdinal()` Method Signatures

There are two versions of the `CompareOrdinal()` method:

  • public static int CompareOrdinal(string first, string second): Compares two entire strings.
  • public static int CompareOrdinal(string str1, int index1, string str2, int index2, int count): Compares portions of two strings, starting at specified indices and considering a given number of characters.

Parameters

The first version takes two strings as input. The second version takes the strings, the starting index for each string, and the number of characters to compare.

Return Value

The method returns an integer representing the comparison result (0, positive, or negative).

Example


using System;

public class StringExample {
    public static void Main(string[] args) {
        string s1 = "hello";
        string s2 = "hello";
        string s3 = "csharp";
        string s4 = "mello";
        Console.WriteLine(string.CompareOrdinal(s1, s2)); // Output: 0
        Console.WriteLine(string.CompareOrdinal(s1, s3)); // Output: 5
        Console.WriteLine(string.CompareOrdinal(s1, s4)); // Output: -5
    }
}