9

I tried to migrate a line of code that uses String.Format twice to the new .NET Framework 6 string interpolation feature but until now I was not successfull.

var result = String.Format(String.Format("{{0:{0}}}{1}", 
    strFormat, withUnit ? " Kb" : String.Empty), 
    (double)fileSize / FileSizeConstant.KO);

A working example could be:

var result = String.Format(String.Format("{{0:{0}}}{1}", 
   "N2", " Kb"), 1000000000 / 1048576D);

which outputs: 953,67 Kb

Is that possible or do we need to use the old construct for this special case?

3
  • 4
    Mine is not an answer, but I'd discourage anyone (me firstly) to put tons of ops in the same line. It's just matter of readability, but then maybe the interpolation can succeed. Commented Jul 14, 2015 at 13:43
  • It's probably not possible with string interpolation since you're injecting a format string (via strFormat). Although it could be simplified as Mario suggests to make it more readable. Commented Jul 14, 2015 at 13:49
  • you can turn the inner string.format to string interpolation but its not possible for the outer string.format. since the given string is variable. Commented Jul 14, 2015 at 13:49

1 Answer 1

6

The main issue lies in strFormat variable, you can't put it as format specifier like this "{((double)fileSize/FileSizeConstant.KO):strFormat}" because colon format specifier is not a part of interpolation expression and thus is not evaluated into string literal N2. From documentation:

The structure of an interpolated string is as follows:
$"<text> { <interpolation-expression> <optional-comma-field-width> <optional-colon-format> } <text> ... } "


You can make format as a part of expression by passing it to double.ToString method:

$"{((double)fileSize/FileSizeConstant.KO).ToString(strFormat)}{(withUnit?" Kb":string.Empty)}";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.