Home > database >  String Interpolation Of Version
String Interpolation Of Version

Time:02-28

I've been converting some code to use string interpolation instead of concatenation but have hit an anomaly with the Version property.

This works as expected:

Dim CurrTime As String = $"Current time is {Now:HH:mm:ss}" (eg Current time is 23:22:21)

But this doesn't:

Dim Ver As String = $"Version is {myAssembly.GetName().Version:3}"

If Version is, say, 1.2.3.4, Ver still resolves to "Version is 1.2.3.4" instead of "Version is 1.2.3" as I would expect.

Am I misinterpreting how this should work? Obviously, it's not a big deal, I'm just confused.

CodePudding user response:

The :formatString part used in composite formatting (e.g., with string interpolation or String.Format()) does not do everything that ToString() does. The former only supports certain types. If you check the docs for Structure of an interpolated string, you'll see that description of the formatString element is:

A format string that is supported by the type of the expression result. For more information, see Format String Component.

And if you follow the link, it takes you to the documentation of composite formatting where you can read more about what types are supported:

The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.

As a workaround, you could combine String.Format() with string interpolation:

Dim Ver As String = $"Version is {myAssembly.GetName().Version.ToString(3)}"

Or just revert to concatenation for this specific case.

  • Related