Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refactor C# interpolated strings to string.Format(...) automatically?

Tags:

string

c#

Recently in C# 6 a new language element/syntactic sugar was introduced named string interpolation.

However after a few minutes of enjoying the sweet taste of this syntax, it quickly turns out, that interpolated strings (what are still string literals in semantic point of view) can not be refactored out to a resource because of the variables embedded are living only that scope where the interpolated string is defined.

This scope locked string literals for example can not be localized and regardless of the localization need, some code quality checkers used to regard string literals embedded in as code smell.

Working with a huge enterprise code base I expect to appear more and more interpolated strings, so the problem will be quickly turn from theoretical to practical. I would like both

  • have a code quality checker rule which bans out this practice just like string literals in the middle of the code (I can manage it, by defining custom rules in the standard quality tools. Although StyleCop currently does not even recognize them, and runs to an internal error, so this will not be as easy as it sounds)
  • have a refactoring tool what can refactor string interpolation to string.Format so then it can easily can refactor out to a standard .NET resource.

Any suggestions

like image 569
g.pickardou Avatar asked Oct 23 '25 14:10

g.pickardou


2 Answers

Enabling code analysis prevents usage of interpolated strings (warning CA1305) as they don't support specifying locale (unlike String.Format). So while somewhat awkward this is possible solution to your particular case.

Also R# can quickly convert one format to another - so while not automated combination of Code Analysis and R# would let you quickly find and partially correct all the cases.

like image 180
Alexei Levenkov Avatar answered Oct 26 '25 04:10

Alexei Levenkov


Localisation is possible with string interpolation.

Consider this:

System.FormattableString s = $"Hello, {name}";

s.ToString() will use the current culture to produce the string.

float flt = 3.141;

System.IFormattable s = $"{flt}";

With IFormattable you can alter numeric formats according to specific languages

So it is possible, just not directly.

source:

https://msdn.microsoft.com/nl-nl/library/dn961160.aspx

like image 24
Serve Laurijssen Avatar answered Oct 26 '25 05:10

Serve Laurijssen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!