I want to test if the StringBuilder
is empty but there is no IsEmpty
method or property.
How does one determine this?
Check if StringBuilder Is Empty Using the Length Property The StringBuilder class has a property named Length that shows how many Char objects it holds. If Length is zero that means the instance contains no characters.
If a variable is null then is not referring to anything. So, if you have StringBuilder s = null , that means that s is of type StringBuilder but it is not referring to a StringBuilder instance. If you have a non- null reference then you are free to call methods on the referred object.
so you can use the fact that StringBuffer. length() returns zero (or not) to check if the buffer is empty (or not).
The length() method of StringBuilder class returns the number of character the StringBuilder object contains. The length of the sequence of characters currently represented by this StringBuilder object is returned by this method.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With