Soft Coding Format Specifier for Interpolated C # 6.0 Strings

I know that we can use the format specifier to interpolate strings in C # 6

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

However, I use the same format in the same method over and over again, so I would like to softly code it, but I'm not sure how to do it or even if it’s 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 this, or confirm to me its impossibility, since I did some reading and did not find anything to suggest it possible

+4
source share
1 answer

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

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);

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

dd-MMM-yyyy , ToString(), .

, string.Format , :

var someString = string.Format(
    " the date was ... {0}",
    _criteria.DateFrom.ToString(formatSpecifier));
+1

Source: https://habr.com/ru/post/1676145/


All Articles