Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9130,5 +9130,81 @@ internal static void Method()
}
");
}

[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestInSwitchExpression1()
{
await TestInRegularAndScriptAsync(
@"
using System;

class Class
{
string Method(int i)
{
return i switch
{
0 => [|Goo|](),
};
}
}",
@"
using System;

class Class
{
string Method(int i)
{
return i switch
{
0 => Goo(),
};
}

private string Goo()
{
throw new NotImplementedException();
}
}");
}

[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestInSwitchExpression2()
{
await TestInRegularAndScriptAsync(
@"
using System;

class Class
{
void Method(int i)
{
var v = i switch
{
0 => """",
1 => [|Goo|](),
};
}
}",
@"
using System;

class Class
{
void Method(int i)
{
var v = i switch
{
0 => """",
1 => Goo(),
};
}

private string Goo()
{
throw new NotImplementedException();
}
}");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ protected override IEnumerable<TypeInferenceInfo> InferTypesWorker_DoNotCallDire
RefExpressionSyntax refExpression => InferTypeInRefExpression(refExpression),
ReturnStatementSyntax returnStatement => InferTypeForReturnStatement(returnStatement),
SubpatternSyntax subpattern => InferTypeInSubpattern(subpattern, node),
SwitchExpressionArmSyntax arm => InferTypeInSwitchExpressionArm(arm),
SwitchLabelSyntax switchLabel => InferTypeInSwitchLabel(switchLabel),
SwitchStatementSyntax switchStatement => InferTypeInSwitchStatement(switchStatement),
ThrowExpressionSyntax throwExpression => InferTypeInThrowExpression(throwExpression),
Expand Down Expand Up @@ -2058,6 +2059,29 @@ private ISymbol GetDeclaredMemberSymbolFromOriginalSemanticModel(SyntaxNode decl
: null;
}

private IEnumerable<TypeInferenceInfo> InferTypeInSwitchExpressionArm(
SwitchExpressionArmSyntax arm)
{
if (arm.Parent is SwitchExpressionSyntax switchExpression)
{
// see if we can figure out an appropriate type from a prior arm.
var armIndex = switchExpression.Arms.IndexOf(arm);
if (armIndex > 0)
{
var previousArm = switchExpression.Arms[armIndex - 1];
var priorArmTypes = GetTypes(previousArm.Expression, objectAsDefault: false);
if (priorArmTypes.Any())
return priorArmTypes;
}

// if a prior arm gave us nothing useful, or we're the first arm, then try to infer looking at
// what type gets inferred for the switch expression itself.
return InferTypes(switchExpression);
}

return SpecializedCollections.EmptyEnumerable<TypeInferenceInfo>();
}

private IEnumerable<TypeInferenceInfo> InferTypeInSwitchLabel(
SwitchLabelSyntax switchLabel, SyntaxToken? previousToken = null)
{
Expand Down