@@ -101,28 +101,31 @@ private static void TryRegisterCodeFixForCast(CodeFixContext context, Diagnostic
101101 async ct =>
102102 {
103103 NullableTypeSyntax newType = SyntaxFactory . NullableType ( type . WithoutTrivia ( ) ) . WithTriviaFrom ( type ) ;
104- Document changedDocument = await context . Document . ReplaceNodeAsync ( type , newType , ct ) . ConfigureAwait ( false ) ;
105104
106- // This could be in a variable declaration, so grab the new syntax root and find the newly-replaced type node
107- SyntaxNode root = await changedDocument . GetSyntaxRootAsync ( ct ) . ConfigureAwait ( false ) ;
108- SyntaxNode insertedNewType = root . FindNode ( type . Span ) ;
109-
110- // Try finding a surrounding variable declaration whose type we also have to change
111- if ( insertedNewType . AncestorsAndSelf ( ) . FirstOrDefault ( a => a . IsKind ( SyntaxKind . EqualsValueClause ) ) is EqualsValueClauseSyntax equalsValueClause )
112- {
113- ExpressionSyntax expression = equalsValueClause . Value ;
114-
115- if ( equalsValueClause . IsParentKind ( SyntaxKind . VariableDeclarator )
116- && equalsValueClause . Parent . Parent is VariableDeclarationSyntax variableDeclaration
117- && variableDeclaration . Variables . Count == 1
118- && ! variableDeclaration . Type . IsKind ( SyntaxKind . NullableType )
119- && variableDeclaration . Type is not IdentifierNameSyntax { Identifier . Text : "var" } )
105+ // This could be in a variable declaration whose type we also may have to change
106+ if ( type . Parent ? . Parent is EqualsValueClauseSyntax
120107 {
121- NullableTypeSyntax newDeclarationType = SyntaxFactory . NullableType ( variableDeclaration . Type . WithoutTrivia ( ) ) . WithTriviaFrom ( variableDeclaration . Type ) ;
122- changedDocument = await changedDocument . ReplaceNodeAsync ( variableDeclaration . Type , newDeclarationType , ct ) . ConfigureAwait ( false ) ;
108+ Parent : VariableDeclaratorSyntax
109+ {
110+ Parent : VariableDeclarationSyntax
111+ {
112+ Variables . Count : 1 ,
113+ Type : { IsVar : false } declarationType
114+ } variableDeclaration
115+ }
123116 }
117+ && ! declarationType . IsKind ( SyntaxKind . NullableType ) )
118+ {
119+ NullableTypeSyntax newDeclarationType = SyntaxFactory . NullableType ( declarationType . WithoutTrivia ( ) ) . WithTriviaFrom ( declarationType ) ;
120+ VariableDeclarationSyntax newVariableDeclaration = variableDeclaration
121+ . ReplaceNode ( type , newType )
122+ . WithType ( newDeclarationType ) ;
123+ return await context . Document . ReplaceNodeAsync ( variableDeclaration , newVariableDeclaration , ct ) . ConfigureAwait ( false ) ;
124+ }
125+ else
126+ {
127+ return await context . Document . ReplaceNodeAsync ( type , newType , ct ) . ConfigureAwait ( false ) ;
124128 }
125- return changedDocument ;
126129 } ,
127130 GetEquivalenceKey ( diagnostic ) ) ;
128131
0 commit comments