Skip to content

Commit a7eb09a

Browse files
committed
Handle NotPattern (RR0133)
1 parent 9e6851b commit a7eb09a

File tree

2 files changed

+55
-2
lines changed

2 files changed

+55
-2
lines changed

src/Refactorings/CSharp/Refactorings/ConvertIfToSwitchRefactoring.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,9 @@ private static (bool success, ExpressionSyntax switchExpression) Analyze(
100100

101101
PatternSyntax pattern = isPatternExpression.Pattern;
102102

103-
SyntaxDebug.Assert(pattern.IsKind(SyntaxKind.DeclarationPattern, SyntaxKind.ConstantPattern), pattern);
103+
SyntaxDebug.Assert(pattern.IsKind(SyntaxKind.DeclarationPattern, SyntaxKind.ConstantPattern, SyntaxKind.NotPattern), pattern);
104104

105-
if (!pattern.IsKind(SyntaxKind.DeclarationPattern, SyntaxKind.ConstantPattern))
105+
if (!pattern.IsKind(SyntaxKind.DeclarationPattern, SyntaxKind.ConstantPattern, SyntaxKind.NotPattern))
106106
return default;
107107

108108
ExpressionSyntax expression = isPatternExpression.Expression.WalkDownParentheses();
@@ -270,6 +270,12 @@ private static SyntaxList<SwitchLabelSyntax> CreateSwitchLabels(IfStatementSynta
270270
{
271271
return SingletonList<SwitchLabelSyntax>(CasePatternSwitchLabel(pattern, Token(SyntaxKind.ColonToken)));
272272
}
273+
else if (pattern.IsKind(SyntaxKind.NotPattern))
274+
{
275+
var notPattern = (UnaryPatternSyntax)pattern;
276+
277+
return SingletonList<SwitchLabelSyntax>(CasePatternSwitchLabel(notPattern, Token(SyntaxKind.ColonToken)));
278+
}
273279
else
274280
{
275281
throw new InvalidOperationException();

src/Tests/Refactorings.Tests/RR0133ConvertIfToSwitchTests.cs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,53 @@ int M()
126126
", equivalenceKey: RefactoringId);
127127
}
128128

129+
[Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.ConvertIfToSwitch)]
130+
public async Task Test_NotPattern()
131+
{
132+
await VerifyRefactoringAsync(@"
133+
class C
134+
{
135+
int M()
136+
{
137+
object x = null;
138+
139+
[||]if (x is string s)
140+
{
141+
return 1;
142+
}
143+
else if (x is not null)
144+
{
145+
}
146+
147+
return 0;
148+
}
149+
}
150+
", @"
151+
class C
152+
{
153+
int M()
154+
{
155+
object x = null;
156+
157+
switch (x)
158+
{
159+
case string s:
160+
{
161+
return 1;
162+
}
163+
164+
case not null:
165+
{
166+
break;
167+
}
168+
}
169+
170+
return 0;
171+
}
172+
}
173+
", equivalenceKey: RefactoringId);
174+
}
175+
129176
[Fact, Trait(Traits.Refactoring, RefactoringIdentifiers.ConvertIfToSwitch)]
130177
public async Task Test_ConstantAndPattern()
131178
{

0 commit comments

Comments
 (0)