62

I'm really excited about the new features in C# 6, including the new string syntax:

var fullName = $"My Name is {FirstName} {LastName}";

However, I can't figure out how to escape quotes inside the braces to do the follow:

bool includePrefix = true;

var fullName = $"My name is {includePrefix ? "Mr. " : ""}{FirstName} {LastName}";

C# 6 doesn't like that. I've had to revert to using String.Format in that second case. Is it possible to escape quotes using the new syntax?

Update: Yes, I have tried using the \ escape, but it's not recognized.

3
  • Write a property that does the property string logic and then just use that in the string instead.
    – asawyer
    Commented Oct 7, 2015 at 20:07
  • 1
    @asawyer I am aware of several workarounds, including one I stated in my question. I'd just like to know if escaping is possible inside this new syntax.
    – Nathan A
    Commented Oct 7, 2015 at 20:08

2 Answers 2

94

wrap your logic inside parentheses, inside the brackets:

var fullName = $"My name is {(includePrefix ? "Mr. " : "")}{FirstName} {LastName}";
0
20

Regularly to escape quotes you need to use a slash (i.e. \").

However, this is not the issue here, as you don't need to escape, you're just missing parentheses over the expression.

This works:

bool includePrefix = true;
var fullName = $"My name is {(includePrefix ? "Mr. " : "")}{FirstName} {LastName}";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.