How to check if a StringBuilder is empty?

Boiethios picture Boiethios · Aug 1, 2017 · Viewed 47.7k times · Source

I must unit test a method that takes a StringBuilder, two items, and fill the StringBuilder with the discrepancies found between the two items.

In my first test, I give to it two identical items, so I want to test if the StringBuilder is empty.

There is no IsEmpty method or property.

How to easily check this?

Answer

Mong Zhu picture Mong Zhu · Aug 1, 2017

If you look at the documentation of StringBuilder it has only 4 properties. One of them is Length.

The length of a StringBuilder object is defined by its number of Char objects.

You can use the Length property:

Gets or sets the length of the current StringBuilder object.

StringBuilder sb = new StringBuilder();

if (sb.Length != 0)
{
    // you have found some difference
}

Another possibility would be to treat it as a string by using the String.IsNullOrEmpty method and condense the builder to a string using the ToString method. You can even grab the resulting string and assign it to a variable which you would use if you have found some differences:

string difference = ""; 

if (!String.IsNullOrEmpty(difference = sb.ToString()))
{
    Console.WriteLine(difference);      
}