Formatting dashes in string interpolation

Gigi picture Gigi · Nov 18, 2014 · Viewed 10.2k times · Source

I have just been checking out the new string interpolation feature in C# 6.0 (refer to the Language Features page at Roslyn for further detail). With the current syntax (which is expected to change), you can do something like this (example taken from a blog post I'm writing just now):

var dob2 = "Customer \{customer.IdNo} was born on \{customer.DateOfBirth:yyyyMdd}";

However, I can't seem to include dashes in the formatting part, such as:

var dob2 = "Customer \{customer.IdNo} was born on \{customer.DateOfBirth:yyyy-M-dd}";

If I do that, I get the error:

Error CS1056 Unexpected character '-' StringInterpolation Program.cs 21

Is there any way I can get dashes to work in the formatting part? I know I can just use string.Format(), but I want to see if it can be done with string interpolation, just as an exercise.

Edit: since it seems like nobody knows what I'm talking about, see my blog post on the subject to see how it's supposed to work.

Answer

Mike Trusov picture Mike Trusov · Aug 27, 2015

The final version is more user friendly:

var text = $"The time is {DateTime.Now:yyyy-MM-dd HH:mm:ss}";