Reputation: 21764
Is there a way to declare strings in C# without having to escape special characters?
I have searched for answers and found some string literal syntaxes that I thought would achieve what I wanted, but did not.
string lit = ""<?xml version="1.0" encoding="utf-8"?""
string lit = @"<?xml version="1.0" encoding="utf-8"?"
error CS1525: Invalid expression term '?'
Upvotes: 1
Views: 3533
Reputation: 62488
inside the string literal if we need to use double quote we will still need to escape it in verbatim string too like:
string lit = @"<?xml version=""1.0"" encoding=""utf-8""?";
the value in variable will be :
<?xml version="1.0" encoding="utf-8"?
Upvotes: 2
Reputation: 1499800
Is there a way to declare strings in C# without having to escape special characters?
When considering "
as a special character, the answer is no.
Verbatim string literals (@"foo"
) avoid you having to escape backslashes and line breaks, but you still need to escape double quotes. The correct escaping for your examples would be:
string lit = "<?xml version=\"1.0\" encoding=\"utf-8\"?";
string lit = @"<?xml version=""1.0"" encoding=""utf-8""?";
I often find that for JSON and XML, in test code at least, it's simplest to use single quotes and then replace them:
string lit = "<?xml version='1.0' encoding='utf-8'?".Replace('\'', '"');
Or for XML you could just use single quotes for attributes anyway.
Upvotes: 9