C# String Equals

String type

String.Equals compares strings. You want to look at some ways of comparing string equality in your C# programs. Find out the easiest ways to check strings for equality, and also how to see if one string is ordered before another. We look at some examples of the Equals, Compare, and CompareTo methods on strings.

These C# example programs use the String.Equals method. They use several syntax forms.

Example

First, we look at how you can compare strings and test equality. Here we see the instance Equals method in part 1 and 2, the op_Equality operator in part 3, and three Compare methods. All of the conditionals in the example evaluate to the Boolean value true.

Program that compares strings for equality [C#]

using System;

class Program
{
    static void Main()
    {
	string a = "a" + 1;
	string b = "a" + 1;

	// 1
	// Compare a to b using instance method on a.
	if (a.Equals(b))
	{
	    Console.WriteLine("a.Equals(b) = true");
	}

	// 2
	// Compare b to a using instance method on b.
	if (b.Equals(a))
	{
	    Console.WriteLine("b.Equals(a) = true");
	}

	// 3
	// Compare a to b with op_Equality
	if (a == b)
	{
	    Console.WriteLine("a == b = true");
	}

	// 4
	// Compare with string.Compare; this returns zero if they are equal
	if (string.Compare(a, b) == 0)
	{
	    Console.WriteLine("string.Compare(a, b) = 0");
	}

	// 5
	// Compare with string.CompareOrdinal
	// This returns zero if the char numeric values are equal
	if (string.CompareOrdinal(a, b) == 0)
	{
	    Console.WriteLine("string.CompareOrdinal(a, b) = 0");
	}

	// 6
	// Compare with instance Compare method
	if (a.CompareTo(b) == 0)
	{
	    Console.WriteLine("a.CompareTo(b) = 0");
	}
    }
}

Output

a.Equals(b) = true
b.Equals(a) = true
a == b = true
string.Compare(a, b) = 0
string.CompareOrdinal(a, b) = 0
a.CompareTo(b) = 0

Description. There are small differences in the behavior of these statements. Parts 1 and 2 require that the string be non-null. This can be problematic in certain algorithms, but good in others.

Equality operator. The most common method for string comparisons is part 3 above. However, for some programmers, the operator overloading can be confusing, and might obscure what the compiler actually does with the expression.

Compare methods. The final three examples above use the special Compare and CompareOrdinal methods, and then the CompareTo instance method. These return an integer indicating whether the first string is larger or smaller alphabetically.

IL

.NET Framework information

We can look into the .NET Framework itself (with a program such as IL Disassembler) to see what the instance Equals method and the equality operator do in the above examples. The Equals method is found in mscorlib.dll and has this internal code:

Equals instance method on string type [C#]

// 1. Equals instance method
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public bool Equals(string value)
{
    if ((value == null) && (this != null))
    {
	return false;
    }
    return EqualsHelper(this, value);
}

Equality operator on string type [C#]

// The == operator overload MSIL:
.method public hidebysig specialname static bool
    op_Equality(string a, string b) cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldarg.1
    L_0002: call bool System.String::Equals(
	string, string)
    L_0007: ret
}

// Calls into this:
public static bool Equals(string a, string b)
{
    return ((a == b) || (((a != null) &&
	(b != null)) && EqualsHelper(a, b)));
}

Benchmark

Performance optimization

To test the code for Equals methods, I ran a simple benchmark of two strings that are equal but don't share a string pool reference. Keep in mind that the string intern pool can complicate benchmarks.

string Equals performance test

Instance Equals method: 2028 ms [faster]
Equality operator ==:   2200 ms

Compare

Here we note the Compare methods and when they are needed in the C# programming language. In the first example in this article, you can see the result of the string.Compare method being tested for a value of zero. When string.Compare returns zero, the strings are equal. It returns 1 or -1 depending on the sorted order of the string parameters. This means that if string.Compare ever returns 1 or -1, the strings are not equal. You can find more information on Compare on this site.

String.Compare Method

Empty string comparisons

FxCop

There are many materials about string.Empty and empty string comparisons. You will find that, as Microsoft FxCop recommends, testing against Length is usually the best way. The string.IsNullOrEmpty method deserves a special mention because it is very efficient and safe for rapidly developed programs.

string.IsNullOrEmpty Method

Case-insensitive comparisons

Programming tip

You can easily compare strings in such a way that their uppercase and lowercase differences are ignored. To do this, use the StringComparison.OrdinalIgnoreCase or other culture-specific methods in the Equals method. This is also possible with the Compare methods. There is more information on this topic at this site.

StringComparison Enum

Summary

The C# programming language

We looked at how you can use the string.Equals and Compare methods. The string.Equals and equal operators have the same use normally. The Compare and CompareTo methods serve a different purpose, primarily being useful for sorting and relative comparisons. Note that other value types have CompareTo methods.

CompareTo Int Method String Type
.NET