How to include a DateTime format as a constant inside string interpolation

I was upgrading some code to use string interpolation, a feature introduced in C# 6, when I ran into a small snag with DateTimes and a format string stored as a constant.

How to include a DateTime format as a constant inside string interpolation

I was upgrading some code to use string interpolation, a feature introduced in C# 6, when I ran into a small snag with DateTimes and format strings.

var name = "Grant";
var message = string.Format("Hello {0}, the date is {1:dd/MM/yyyy}.", name, DateTime.Now);
Console.WriteLine(message);

// output: Hello Grant, the date is 04/04/2019.

Updating the string.Format to use string interpolation was straight-forward.

var name = "Grant";
var message = $"Hello {name}, the date is {DateTime.Now:dd/MM/yyyy}.";
Console.WriteLine(message);

// output: Hello Grant, the date is 04/04/2019.

Until I tried to move the format string into a constant so I could use it in several places. The output looks funky because the F and M in "DATE_FORMAT" are valid formats (for tenths of a second and month, respectively).

const string DATE_FORMAT = "dd/MM/yyyy";  // ignored

var name = "Grant";
var message = $"Hello {name}, the date is {DateTime.Now:DATE_FORMAT}.";
Console.WriteLine(message);

// output: Hello Grant, the date is DATE_9OR4AT.

The solution was obvious once I realized it... just use the overloaded ToString() method that accepts a format string. Obvious in hindsight, but it took a few minutes to realize it.

const string DATE_FORMAT = "dd/MM/yyyy";

var name = "Grant";
var message = $"Hello {name}, the date is {DateTime.Now.ToString(DATE_FORMAT)}.";
Console.WriteLine(message);

// output: Hello Grant, the date is 04/04/2019.

And what is string interpolation? According to MSDN, it's just syntactic sugar around the traditional String.Format method:

At compile time, an interpolated string is typically transformed into a String.Format method call. That makes all the capabilities of the string composite formatting feature available to you to use with interpolated strings as well.

IMO, it looks better, reads better, and is more convenient too.

Other Resources

Want to learn more? Start here: