@@ -870,7 +870,10 @@ private static CasePatternSwitchLabelSyntax VarWhen(SyntaxToken varName, Express
870870 SyntaxList < StatementSyntax > stmts = SyntaxFactory . List < StatementSyntax > ( ) ;
871871 ExpressionSyntax exprWithoutSideEffects ;
872872 ExpressionSyntax reusableExprWithoutSideEffects ;
873- if ( ! await CanEvaluateMultipleTimesAsync ( vbExpr ) ) {
873+ if ( IsReusableReadOnlyLocalKind ( _semanticModel . GetSymbolInfo ( vbExpr ) . Symbol ) || await CanEvaluateMultipleTimesAsync ( vbExpr ) ) {
874+ exprWithoutSideEffects = expr ;
875+ reusableExprWithoutSideEffects = expr . WithoutSourceMapping ( ) ;
876+ } else {
874877 TypeSyntax forceType = null ;
875878 if ( _semanticModel . GetOperation ( vbExpr . SkipIntoParens ( ) ) . IsAssignableExpression ( ) ) {
876879 forceType = SyntaxFactory . RefType ( ValidSyntaxFactory . VarType ) ;
@@ -880,14 +883,13 @@ private static CasePatternSwitchLabelSyntax VarWhen(SyntaxToken varName, Express
880883 var ( stmt , id ) = CreateLocalVariableWithUniqueName ( vbExpr , variableNameBase , expr , forceType ) ;
881884 stmts = stmts . Add ( stmt ) ;
882885 reusableExprWithoutSideEffects = exprWithoutSideEffects = id ;
883- } else {
884- exprWithoutSideEffects = expr ;
885- reusableExprWithoutSideEffects = expr . WithoutSourceMapping ( ) ;
886886 }
887887
888888 return ( reusableExprWithoutSideEffects , stmts , exprWithoutSideEffects ) ;
889889 }
890890
891+ private static bool IsReusableReadOnlyLocalKind ( ISymbol symbol ) => symbol is ILocalSymbol ls && ( VBasic . VisualBasicExtensions . IsForEach ( ls ) || ls . GetIsUsing ( ) ) ;
892+
891893 private ( StatementSyntax Declaration , IdentifierNameSyntax Reference ) CreateLocalVariableWithUniqueName ( VBSyntax . ExpressionSyntax vbExpr , string variableNameBase , ExpressionSyntax expr , TypeSyntax forceType = null )
892894 {
893895 var contextNode = vbExpr . GetAncestor < VBSyntax . MethodBlockBaseSyntax > ( ) ?? ( VBasic . VisualBasicSyntaxNode ) vbExpr . Parent ;
@@ -903,7 +905,7 @@ private static CasePatternSwitchLabelSyntax VarWhen(SyntaxToken varName, Express
903905
904906 private async Task < bool > CanEvaluateMultipleTimesAsync ( VBSyntax . ExpressionSyntax vbExpr )
905907 {
906- return _semanticModel . GetConstantValue ( vbExpr ) . HasValue || vbExpr . SkipIntoParens ( ) is VBSyntax . NameSyntax ns && await IsNeverMutatedAsync ( ns ) ;
908+ return _semanticModel . GetConstantValue ( vbExpr ) . HasValue || vbExpr . IsKind ( VBasic . SyntaxKind . MeExpression ) || vbExpr . SkipIntoParens ( ) is VBSyntax . NameSyntax ns && await IsNeverMutatedAsync ( ns ) ;
907909 }
908910
909911 private async Task < bool > IsNeverMutatedAsync ( VBSyntax . NameSyntax ns )
0 commit comments