Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 684
Gigi Avatar asked Nov 18 '14 21:11

Gigi


People also ask

Which character should be used for string interpolation?

To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal. The expression that produces a result to be formatted.

Can we use expressions Inside string interpolation?

String interpolation is a technique that enables you to insert expression values into literal strings. It is also known as variable substitution, variable interpolation, or variable expansion. It is a process of evaluating string literals containing one or more placeholders that get replaced by corresponding values.

How does string interpolation perform?

String interpolation is a process of injecting value into a placeholder (a placeholder is nothing but a variable to which you can assign data/value later) in a string literal. It helps in dynamically formatting the output in a fancier way. Python supports multiple ways to format string literals.

What does string formatting mean?

String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text.


2 Answers

The final version is more user friendly:

var text = $"The time is {DateTime.Now:yyyy-MM-dd HH:mm:ss}";
like image 184
Mike Trusov Avatar answered Oct 14 '22 14:10

Mike Trusov


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"}";
like image 20
svick Avatar answered Oct 14 '22 13:10

svick