C# StringBuilder Equals (If Chars Are Equal)Use the Equals method on StringBuilder to compare the contents of 2 StringBuilders.
Two StringBuilder instances may have the same string contents. We test them for equality. The Equals instance method is ideal for this. It doesn't copy any characters or cause excessive method calls.StringBuilder
First, we use Equals on StringBuilder. The example shows an equality test that succeeds. The 2 StringBuilder objects in the example both contain the same chars and have the same capacity.
Important: We can test StringBuilder references for equality using "==", but this uses the Object.Equals method, which is defined on the object type.
And: The test would not succeed because the two references are different. It does not test the character contents.Object
C# program that uses StringBuilder Equals method
static void Main()
// Create two StringBuilders with the same contents.
StringBuilder builder1 = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
// See if the StringBuilder contents are equal.
// if (builder1 == builder2)
The StringBuilder instance Equals method returns true when three conditions are true. Two objects must have the same capacity, the same MaxCapacity, and the same characters in their buffers.True, False
Tip: If you create two StringBuilders with the same contents but with different capacities, they will not evaluate true.
If you need to test two StringBuilders that may have different capacities but the same contents, you can iterate through their characters with the indexer. You can loop through the entire Length.
Note: This requirement is unlikely, but you may need to develop a custom Equals method.
Summary. We used 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.
© 2007-2020 sam allen. send bug reports to email@example.com.