2
Reply

String.Format and the Ampersand problem

Ask a question
Paula

Paula

17y
8.3k
1
I'm having a little issue with string.format and the use of composite formatting to build a little string.

Here is an example:

x is basically an invalid character, and amongst other things x could be an &

string badString = x.ToString();

string error =
string.Format(@"The variable name has invalid characters: ""{0}""", badString);

works fine if the invalid character is ! or " or £ well anything.... but the ampersand causes concatenation.

Example with a ^ as invalid character:
The variable name has invalid characters: "^"

With an ampersand:
The variable name has invalid characters: ""   <----- I really want an & in there.

No matter what I try to do I just can't seem to get the "&" result.

I don't want to have to write an if statement to qualify what characters are in there if I can avoid it.

Thanks for your help :)


Answers (2)