Checking if stringbuilder is empty

To check if a stringbuilder is empty, use the Length property.

i.e

private readonly StringBuilder builder = new StringBuilder();

public void AddSomeString(string someString)
{
  if (builder.Length > 0) builder.Append(", ");
  
  builder.Append(someString);
}

public string CommaSeparatedString
{
  get
  {
    return builder.ToString();
  }
}
  1. says:

    thank you, I can here the new knowledge

  2. mariam says:

    thank you, this was very useful

  3. Olivier says:

    Does StringBuilder.Lenght has a hidden CPU cost?Is it a O(1) or a O(N) complexity (with N the number of appended messages)?

  4. taragui says:

    thanks