Home
C#
StringBuilder Equals
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 24, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.