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.
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.
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.
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.
String formatting is also known as String interpolation. It is the process of inserting a custom string or variable in predefined text.
The final version is more user friendly:
var text = $"The time is {DateTime.Now:yyyy-MM-dd HH:mm:ss}";
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"}";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With