Search code examples
c#string-interpolationc#-6.0

How do you enter quote characters in C# 6.0 string interpolations


Given

IDictionary<string, string> x;

previously you could do (as an example of the parameter code having quote marks):

string.Format("{0}", x["y"]);

What is the proper way to format the C# 6.0 string interpolation?

$"{x["y"]}"   // compiler error due to the quotes on the indexer value
              // UPDATE:  actually does work, must have had another typo I missed

Escaping the quotes as

\"

doesn't work, and doing

 var b = "y";
 ...
 $"{x[b]}"

seems awkward.


Solution

  • This works for me:

    var dictionary= new Dictionary<string, string>();
    dictionary.Add("x","value of x");
    Console.WriteLine($"x is {dictionary["x"]}");
    

    Make sure your project is set to use the version 6.0 of C# Language level (it's the default option on VS2015).

    Edit: You can also try it here. (make sure you check the "C# 6.0 Beta").