-
Notifications
You must be signed in to change notification settings - Fork 4.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Enhance CA1305 analyzer to cover interpolated strings #88902
Comments
Moving to dotnet/runtime for triage. I guess the primary question would be whether we want to enhance the existing rule or use a different rule ID? |
Tagging subscribers to this area: @dotnet/area-system-runtime Issue DetailsDescribe the problem you are trying to solveThe existing var formatted = $"Date: {DateTime.Now}"; Describe suggestions on how to achieve the ruleThe existing analyzer could be enhanced, so that it would report diagnostic and recommend using new
|
This needs more thought/consideration, namely updating the top post to more clearly provide some example code showing what's happening today vs what's expected to happen and be suggested by the analyzer. We should take into account https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated#implicit-conversions-and-how-to-specify-iformatprovider-implementation and the different ways format providers can be provided alongside string interpolation |
@tannergooding I added some examples to the description. |
Describe the problem you are trying to solve
The existing
CA1305: Specify IFormatProvider
rule does no seem to cover interpolated strings. Currently compiler emits no warning if a value that can be formatted is used inside an interpolation expression:Describe suggestions on how to achieve the rule
The existing analyzer could be enhanced, so that it would report diagnostic and recommend using new
string.Create(IFormatProvider, ref DefaultInterpolatedStringHandler)
overloads if type of the value used in interpolation expression implementsISpanFormattable
(I'm aware that it's actually used instead of callingToString
). Does that make sense? If so, I could try contributing myself as I have experience writing analyzers for Microsoft projects.Examples
If type of the value implements
IFormattable
/ISpanFormattable
which are types that default interpolated string handler special-cases when formatting a value, then compiler could recommend a call tostring.Create
with format provider supplied explicitly:If an interpolated string is implicitly cast to
FormattableString
, thenstring.Create
would also be a more efficient alternative:Or
In case of
IFormattable
, it allows passingnull
as a format provider. Maybe this could be addressed as well, but it's not related specifically to interpolated strings:The text was updated successfully, but these errors were encountered: