diff --git a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs index d129d45bffc92bbf83cccce0d753ac7019674bc1..dbb0c7bdc75e1f0eae57d542baf1623dbf2f30a0 100644 --- a/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs +++ b/src/Analyzers/CSharp/Tests/RemoveUnnecessaryCast/RemoveUnnecessaryCastTests.cs @@ -1814,6 +1814,35 @@ static void Main() await VerifyCS.VerifyCodeFixAsync(source, source); } + [WorkItem(46423, "https://github.com/dotnet/roslyn/issues/46423")] + [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryCast)] + public async Task DoNotCrashWhenTypeCantBeDetermined() + { + var source = +@" +class Other +{ + public short GetScopeIdForTelemetry(FixAllScope scope) + => (short)(scope switch + { + FixAllScope.Document => 1, + FixAllScope.Project => 2, + FixAllScope.Solution => 3, + _ => 4, + }); + + public enum FixAllScope + { + Document, + Project, + Solution, + Other + } +}"; + + await VerifyCS.VerifyCodeFixAsync(source, source); + } + [WorkItem(545777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545777")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryCast)] public async Task DoNotRemoveImportantTrailingTrivia() diff --git a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs index 3872605c6606d7a79352ae9cb0abb994f39e11d5..f4ea54757dedff77ac8a3b895d878ecf01797d22 100644 --- a/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs +++ b/src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Simplification/Simplifiers/CastSimplifier.cs @@ -339,15 +339,15 @@ private static bool IsObjectCastInInterpolation(ExpressionSyntax castNode, IType // The type in `(Type)...` or `... as Type` var castType = semanticModel.GetTypeInfo(castNode, cancellationToken).Type; + // If we don't understand the type, we must keep it. + if (castType == null) + return true; + // The type in `(...)expr` or `expr as ...` var castedExpressionType = semanticModel.GetTypeInfo(castedExpressionNode, cancellationToken).Type; var conversion = semanticModel.ClassifyConversion(castNode.SpanStart, castedExpressionNode, castType, isExplicitInSource: true); - // If we don't understand the type, we must keep it. - if (castType == null) - return true; - // If we've got an error for some reason, then we don't want to touch this at all. if (castType.IsErrorType()) return true;