tags:

views:

100

answers:

5

I am using a string builder as part of a logging process. my seperator character I am using is " ". How can I output this char in a more effective way than simply " ".

For example:

sb.Append(" ");

Or this this the acceptable way to do this?

Thanks in advance

+2  A: 

This is perfectly fine.

However, you may want to raise the abstraction level a bit:

public static StringBuilder AppendWithSeparator(this StringBuilder sb, string value)
{
    sb.Append(value);
    sb.Append(" ");

    return sb;
}
Anton Gogolev
+5  A: 

If it is a single character better use sb.Append(' ');

Mart
Why is this better? See Mark Byers' answer regarding compiler optimisation
Rob Cowell
@Rob Cowell: This has nothing to do with compiler optimization. The `Append(char)` overload doesn't have to check for a null argument or for the parameter length (always 1).
280Z28
+7  A: 

If you're worried that it's going to create a new string object each time, stop worrying. The compiler will optimize it to use the same string object on every call.

Mark Byers
+1 and accepted answer.
JL
+3  A: 

You are probably thinking there is an alternative like string.Empty for "". But there is no such thing, so using " " is ok.

Gerrie Schenck
+2  A: 

You may be better having a const char seperator = ' ' defined somewhere. Then using sb.Append(seperator)

That would make the code more maintainable if at a later point you decide to use (eg) comma seperation.

PaulG