Gigi
Gigi

Reputation: 29421

Formatting dashes in string interpolation

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.

Upvotes: 28

Views: 13166

Answers (2)

Mike Trusov
Mike Trusov

Reputation: 1998

The final version is more user friendly:

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

Upvotes: 60

svick
svick

Reputation: 244777

With the version of string interpolation that's in VS 2015 Preview, you can use characters like dashes in the interpolation format by enclosing it in another pair of quotes:

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

Upvotes: 7

Related Questions