Search code examples
c#stringdouble-quotessingle-quotes

Is there a way to alternate single and double quotes in C# like you can in javascript?


In javascript I can write

    var s = 'He said "Hello" to me';
    or 
    var s = "don't be sad";

In other words, if I want a double quote in the string, I can declare the string using single quotes. If I want a single quote in the string, I can declare the string using double quotes. This is super handy. Has anyone found a way to do something similar in C#?

The single quotes are easy, c# already works with embedding single quotes. As for double quotes, there seems to be 2 common options.

  1. use backslash escape character

    var s = "He said \"Hello\" to me";
    
  2. use single quotes and replace them with double quotes

    var s = "He said 'Hello' to me";
    s = s.Replace("'","\"");
    

I can live with option 2, but better is better.


Solution

  • You can define your extension method on string to little speedup your work and reduce chance to misstype something.

        public static string ApostrophesToQuotes(this string s)
        {
            return s.Replace('\'', '"');
        }
    

    And there is one more way to write quotes in string literal.

    var s = @"he said ""Hello"" to me");
    

    But you can't mix them, because apostrophes are for single character literal (2 byte integer in UTF-16) and quotes are for string literals (array of characters).