This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# String Comparison Functions

The twenty-third part of the C# Fundamentals tutorial continues the examination of the string manipulation functionality provided by the String class. This article investigates methods available for comparing the contents of strings.

CompareOrdinal Method

The CompareOrdinal static method allows case-sensitive comparison of two strings. It differs from Compare in that the comparison result is based upon the numeric Unicode values for each character. As the importance of characters in a cultural context can be different to the fixed numeric ordering of Unicode, different results may occur when comparing using this method. This is shown in the following example, which assumes a UK English configuration:

string animal1 = "Cat";
string animal2 = "cat";                             // Note use of lower case
int result;

result = String.Compare(animal1, animal2);          // result is greater than zero
result = String.CompareOrdinal(animal1, animal2);   // result is less than zero

Equals Method

The Equals method is included for completeness. It returns a Boolean result indicating if two strings match, similar to the equality operator (==). The method can be used against a string object with a single parameter or as a static member with two parameters for the strings to be compared.

string animal = "Cat";
bool result;

result = animal.Equals("Cat");                      // result = true
result = animal.Equals("cat");                      // result = false
result = String.Equals(animal, "Cat");              // result = true
result = String.Equals(animal, "cat");              // result = false

.NET 2.0 IsNullOrEmpty Method

Sometimes it is necessary to check if a string is either empty or is undefined (null). Using .NET 1.1, this would require two tests. The .NET framework 2.0 introduces a new static method, named IsNullOrEmpty, which performs both tests with one statement. The method returns true when the string is empty or null.

string animal1 = "Cat";
string animal2 = "";
string animal3 = null;
bool result;

result = String.IsNullOrEmpty(animal1);             // result = false
result = String.IsNullOrEmpty(animal2);             // result = true
result = String.IsNullOrEmpty(animal3);             // result = true
5 December 2006