Search code examples
c#double-quotesstring-interpolation

String interpolation add quotes around a word


I am trying add quotes in between eventTime variable. But getting compile time error for both code statements below.

Code:

string message  = string.Format("Your event # {0}, is started at "{1}" in Texas.", eventId, eventTime);

string message  = $"Your event # {eventId}, is started at " + {eventTime} + "  in Texas.";

Expected Output:

Your event # 1, is started at "2" in Texas.

This may be simple, But I am not able to find proper syntax for this.

Any help would be Great.

Note:

Because of down votes , I know I have to escape double quotes so I followed this post and tried to escape , But it failed. So I posted the question to know proper syntax. Thanks to all , this helped me to learn , so below is my answer:

Using verbatim string literal.

string message  = $@"Your event # {eventId}, is started at ""{eventTime}""  in Texas.";

Hope helps someone.


Solution

  • Use the escape character \ like this:

    string message = $"Your event # {eventId}, is started at \"{eventTime}\" in Texas.";
    

    message then contains

    Your event # 1, is started at "2" in Texas.
    

    given that eventId == 1 and eventTime == 2.

    The escape sequence \" marks the quoatation marks part of the string, thus not terminating it.