You have two StringBuilder instances that may have the same string contents, and you can want to test them for equality. The Equals instance method is ideal for this, as it doesn't copy any characters or cause excessive method calls. Here we look at an example of using the Equals instance method on StringBuilder. We also test the equality operator on StringBuilder, using the C# programming language.
First, we look at how you can use Equals on StringBuilder. The below example shows an equality test that succeeds. The two StringBuilder objects in the example both contain the same characters "One two" and have the exact same capacity.
::: Program that uses StringBuilder Equals method (C#) :::
using System;
using System.Text;
class Program
{
static void Main()
{
//
// Create two StringBuilders with the same contents.
//
StringBuilder builder1 = new StringBuilder();
builder1.Append("One ");
builder1.Append("two");
StringBuilder builder2 = new StringBuilder();
builder2.Append("One ");
builder2.Append("two");
//
// See if the StringBuilder contents are equal.
//
if (builder1.Equals(builder2))
{
Console.WriteLine("Equal");
}
// if (builder1 == builder2)
// {
// Console.WriteLine("Equal");
// }
}
}
::: Output of the program :::
EqualThe commented out lines. Near the end of the example, you will see four lines that are commented out. You can test StringBuilder references for equality using ==, but this just uses the Object.Equals method, which is defined on the object type for all instances. The test would not succeed because the two references are different.
The StringBuilder instance Equals method returns true if and only if the two StringBuilder objects have the same capacity, the same MaxCapacity, and the same characters in their buffers. If you create two StringBuilders with the same contents but with different capacities, they will not evaluate true. This article is based on .NET 3.5 SP1.
If for some reason you need to test two StringBuilders that may have different capacities but the same contents, you can iterate through their characters with the indexer and loop through the entire Length. This requirement is unlikely, but you may need to develop a custom Equals method.
Here we saw how you can use the Equals instance method on StringBuilder. This method is overridden and provides a powerful and efficient way to test two StringBuilders for equality. There are other ways of testing them, but they are more cumbersome.