StringBuilder
Equals
Two StringBuilder
instances may have the same string
contents. We test them for equality. The Equals
instance method is ideal for this.
Equals()
doesn't copy any characters or cause excessive method calls. But it will check the capacities of the StringBuilders
.
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.
StringBuilder
references for equality using the equality operator, but this uses the Object.Equals
method.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
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.
StringBuilders
with the same contents but with different capacities, they will not evaluate true.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.
Equals
method.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.