Does string.Format add extra quotes to value

261 views Asked by At

I discovered that whenever I use this method string.Format(), it adds extra quotes and backslash to my variable value.

string value = string.Format("sample {0}", someText);

On VS Watch, I see this result:

"sample \"blah\""

In Text Visualizer, I get this:

sample "blah"

Can anyone tell me why I can't get this?

"sample blah"

Please note: I have a workaround already which is string.Replace("\"","") but I just want to know where the extra quotes was added.

5

There are 5 answers

1
Andrei Tătar On BEST ANSWER

I'm 100% sure, in your context, sometext contains the extra quotes.

string.Format("sample {0}", "blah")

returns "sample blah"

0
MakePeaceGreatAgain On

This relates only to VS Debugging. It´s not ACTUALLY adding anything to that string. VS is just escaping strings, nothing to worry about or to handle with.

EDIT: To get sample blah (without ANY quotes) instead of sample "blah" you need to replace the quotes:

Console.WriteLine(value.Replace("\"", "");

Now within VS Debugger you see the following: "sample blah" whilst within a text-file e.g. you´ll see sample blah

0
Spider man On

It shows your sometext contains "blah" instead of blah. That is why \" is appearing during debug.

0
Soner Gönül On

This string.Format doesn't add anything to any string at all.

The difference is how you can see your string in a Visual Studio and in a Text Visualizer. Since because " is an escape sequence character, you need to use it as \" in your code part.

As far as I know, these escape sequence characters are legacy from C language standard.

Can anyone tell me why I can't get this?

"sample blah"

Because you didn't do anything to get this string in your example. Your string doesn't have an escaped " character at start or in the end. You can use escape them in your string.format like;

string someText = "blah";
string value = string.Format("\"sample {0}\"", someText); 

Result will be;

"sample blah"
0
Spike On

Your format string doesn't have any quotes in it. If you want the string to contain quotes you need to add quotes to the format string.

string foo = "foo" foo has the value foo

string foo = "\"foo\"" foo has the value "foo"