dotnet / dotnet/roslyn

"Convert to switch expression" refactoring for ternary statements

Open
#75,973 1 comment 0 reactions 0 assignees View on GitHub
Area-IDE
Dominant language
C#
Stars
20.7k
Forks
4.3k
PR merge metrics
PR metrics pending

Description

**Brief description:**

Light up the "Convert to switch expression" refactoring for ternary statements.

This is a style preference.

**Code example that the analyzer should report:**

Currently, the code

```cs
static string? Case1(ReadOnlySpan source)
{
var i = source.IndexOf(':');

var substring = i < 0
? null
: source[i..].ToString();

return substring;
}
```

_Sequentially_ has the possible refactorings,

1. Replace conditional expression with statements
2. Convert to switch statement
3. Convert to switch expression

It would be nice if it would suggest all three in the first instance, rather than requiring one or two transformations first. I.e., suggest the refactoring from ternary to,

```cs
static string? Case1(ReadOnlySpan source)
{
var i = source.IndexOf(':');

var substring = i switch
{
< 0 => null,
_ => source[i..].ToString(),
};

return substring;
}
```

Contributor guide

Open the contributing guide

Research direction

Start by locating the existing "Convert to switch expression" refactoring and the ternary or conditional-expression refactoring entry point. Compare the current sequential refactorings using the Case1 example, then verify that a ternary can directly produce the shown switch expression while preserving the existing alternatives.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.