Roslyn: Support Interpolating Ternary Operations

Created on 24 Oct 2020  路  4Comments  路  Source: dotnet/roslyn

Brief description:
It would be nice if Roslyn would offer to interpolate cases where a ternary operator has been slammed in the front (or back end) of a interpolated string.

Languages applicable:

My request would be C# only; but I can't see why it wouldn't work in VB.NET

Code example that the analyzer should report:

(validateOnly ? "Validating" : "Sorting") + $" solution `{targetArgument}`";

Can be Converted to

$"{(validateOnly ? "Validating" : "Sorting")} solution `{targetArgument}`"

Additional information:
The reason a user might have written the above is they've encountered an error when attempting to originally interpolate the string, not realizing that you can wrap it in (). See https://github.com/dotnet/roslyn/issues/21259 This stack overflow issue shows that there are at least a couple hundred users attempting to use this within an interpolated string https://stackoverflow.com/questions/31844058/how-to-use-the-ternary-operator-inside-an-interpolated-string

Documentation requirements:

When this analyzer is implemented, it must be documented by following the steps at Documentation for IDE CodeStyle analyzers.

Area-Analyzers Area-IDE Concept-Continuous Improvement help wanted

All 4 comments

I think we might accept a feature where a concatenated string (regardless of what the exprs are) can become an interpolated string. I don't really see why this would need to be restricted for conditional exprs.

The current solution does not support inlining of other interpolated strings:

// Before
var s = $"s" + (true ? "t" : "f");
// Expected
var s = $"s{true ? "t" : "f"}";
// Actual
var s = $"{$"s"}{(true ? "t" : "f")}";

There are two problems:

  • The interpolated string $"s" is not inlined
  • The parentheses were not removed

I solved both of these problems in #49207, but the solution I used there should be integrated into the existing provider.

I created a new PR with a fix in the right location: #49229

Was this page helpful?
0 / 5 - 0 ratings