views:

156

answers:

3

StringBuilder.ToString() is adding '\' characters in the beginning and ending of the string.

Why is this?

Before calling .ToString() the string doesn't have the '\' character.

+1  A: 

What text do you have in the StringBuilder?

The following code just writes out "hello" for me

var sb = new StringBuilder();
sb.Append("hello");
var test = sb.ToString();
Console.WriteLine(test);

Am I missing something?

Quinn351
That's not really an answer as you sound really unsure, as well as the question is just wrong in its current state..
Dykam
@Dykam: I think this is a useful answer. It provides the OP with a correctly working sample.
0xA3
@Dykam that may be because I don't get the same result as the person asking the question and he didn't give me much to go on
Quinn351
Quite true, but IMO it feels a bit like a comment.
Dykam
+1  A: 

StringBuilder does not add any characters besides those you have appended. Perhaps you are looking at the Debug View of a string created by string builder and characters which may need to be escaped have the backslash (\) in front of them for convenience of copying the debug output.

The \ characters are not actually in the string data itself, but rather part of the display of the string.

Edit: here is a test you can run

private static void TestStringBuilder()
{
    StringBuilder builder = new StringBuilder();
    builder.Append(@"""saoetuhasoethuasteuhasoetnuh""");
    foreach (char c in builder.ToString())
    {
        System.Diagnostics.Debug.Assert(c != '\\', "EPIC STRINGBUILDER FAIL");
    }
}
sixlettervariables
+13  A: 

Are you thinking of these backslashes here?

Example screenshot showing backslashes in the Watch window

If so, you are misreading the output: The backslashes are not actually in the string. They are only displayed here to make the representation valid according to C# syntax. If you were to output the string using Console.WriteLine, for example, it would not have backslashes.

To be fair, it is inconsistent. The debug view for the StringBuilder doesn’t have the backslashes, but the one for strings does.

Timwi
+1, Nice screen shot
Kirk Woll
[Thankies!](http://meta.stackoverflow.com/questions/700/)
Timwi
This is because of the quote you'e added. The "\" is not really present in te string. It's just a visualisation of the debugger. Click on the magnifier and you'll see the real text in the stringbuilder!
Scordo
@Kirk Woll: Now with drop shadow! :-D
Timwi
Hey, flaggers, Hans was joking, you can stop flagging his comment now.
Will
@Timwi That is offensive? You know, he didn't actually downvote. Click your votecount and you can see this.
Will