Home
C#
StringBuilder Equals
Updated Aug 24, 2023
Dot Net Perls
StringBuilder Equals. Two StringBuilder instances may have the same string contents. We test them for equality. The Equals instance method is ideal for this.
Method notes. Equals() doesn't copy any characters or cause excessive method calls. But it will check the capacities of the StringBuilders.
StringBuilder
Example code. The example shows an Equals 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 the equality operator, but this uses the Object.Equals method.
And The test would not succeed because the two references are different. It does not test the character contents.
object
using System; using System.Text; // 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"); }
Equal
Implementation. Equals returns true when 3 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.
Contents. Sometimes you may need to test 2 StringBuilders that may have different capacities but the same contents. To do this, iterate through their characters with the indexer.
Note This requirement is unlikely, but you may need to develop a custom Equals method.
A 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 24, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen