How to check if a StringBuilder is empty?

C#Conditional StatementsStringbuilder

C# Problem Overview


I want to test if the StringBuilder is empty but there is no IsEmpty method or property.

How does one determine this?

C# Solutions


Solution 1 - C#

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);		
}

Solution 2 - C#

use the StringBuilder.Length Property, here the doc

if (mySB.Length > 0)
{
     Console.WriteLine("Bang! is not empty!"); 
}

Solution 3 - C#

Use this, it will work:

StringBuilder stringbuilder = new StringBuilder();
if(string.isnullorempty(Convert.toString(stringbuilder)))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBoiethiosView Question on Stackoverflow
Solution 1 - C#Mong ZhuView Answer on Stackoverflow
Solution 2 - C#ΦXocę 웃 Пepeúpa ツView Answer on Stackoverflow
Solution 3 - C#Ajith KumarView Answer on Stackoverflow