Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace double String.Format with string interpolation

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?

like image 622
Bidou Avatar asked Jul 14 '15 13:07

Bidou


People also ask

Is string format faster than interpolation?

The InterpolateExplicit() method is faster since we now explicitly tell the compiler to use a string . No need to box the object to be formatted.

Can I use string interpolation?

Beginning with C# 10, you can use string interpolation to initialize a constant string. All expressions used for placeholders must be constant strings. In other words, every interpolation expression must be a string, and it must be a compile time constant.

What does string interpolation do?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

What is the correct syntax for string interpolation?

Syntax of string interpolation starts with a '$' symbol and expressions are defined within a bracket {} using the following syntax. Where: interpolatedExpression - The expression that produces a result to be formatted.


1 Answers

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)}";
like image 98
Leonid Vasilev Avatar answered Sep 25 '22 19:09

Leonid Vasilev