Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Soft coding format specifier for Interpolated strings c# 6.0

I know that we can use a format specifier for string interpolation in C#6

var someString = $" the date was ... {_criteria.DateFrom:dd-MMM-yyyy}";

However I am using the same format in the same method over and over again so would like to soft code it, but not sure how to do it, or even if its possible,

DateTime favourite;
DateTime dreaded;

...
...

const string myFormat = "dd-MMM-yyyy";

var aBigVerbatimString = $@"
    my favorite day is {favourite:$myFormat}
    but my least favourite is {dreaded:$myFormat}
    blah
    blah
   ";

Can someone tell me how to do it, or confirm to me its impossible as I have done some reading and found nothing to suggest its possible

like image 620
Max Carroll Avatar asked Oct 30 '22 08:10

Max Carroll


1 Answers

String interpolation is compiled directly into an equivalent format statement, so

var someString = $" the date was ... {_criteria.DateFrom:dd-MMM-yyyy}";

becomes literally

var someString = string.Format(
    " the date was ... {0:dd-MMM-yyyy}",
    _criteria.DateFrom);

which is functionally equivalent to

var someString = string.Format(
    " the date was ... {0}",
    _criteria.DateFrom.ToString("dd-MMM-yyyy"));

Because the compiler ultimately treats the dd-MMM-yyyy as a string literal to be passed to the ToString() method, there is no way to avoid hardcoding when using this idiom.

If you would like to softcode the format specifier string, you could opt to use string.Format directly, as follows:

var someString = string.Format(
    " the date was ... {0}",
    _criteria.DateFrom.ToString(formatSpecifier));
like image 178
Robin James Kerrison Avatar answered Nov 15 '22 05:11

Robin James Kerrison