How to check if StringBuilder is empty?

I have a unit test method that accepts StringBuildertwo elements and fills in the StringBuilderinconsistencies found between the two elements.

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

There is no method or property IsEmpty.

How easy is it to check it?

+6
source share
4 answers

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

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

Length:

StringBuilder.

StringBuilder sb = new StringBuilder();

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

, String.IsNullOrEmpty ToString . , , :

string difference = ""; 

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

StringBuilder.Length, doc

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

Use this, it will work:

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

We can verify that StringBuilder is empty.

Or:

StringBuilder sb = new StringBuilder();
if(sb.Length > 0) { 
   //Your code goes here..
}else{
  //StringBuilder is Empty
}

OR

StringBuilder sb = new StringBuilder();
if(!String.IsNullOrEmpty(sb.ToString()){
     //Your code goes here..
}else{
    //StringBuilder is Empty
}
-4
source

All Articles