diff --git a/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/VariableDeclaredInWideScopeIssue.cs b/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/VariableDeclaredInWideScopeIssue.cs index 6ce291b7fc..b43fe993fe 100644 --- a/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/VariableDeclaredInWideScopeIssue.cs +++ b/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/VariableDeclaredInWideScopeIssue.cs @@ -51,17 +51,22 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring this.context = context; } - static IList loopStatements = new List() { + static IList blockingStatements = new List() { typeof(WhileStatement), typeof(ForeachStatement), typeof(ForStatement), - typeof(DoWhileStatement) + typeof(DoWhileStatement), + typeof(TryCatchStatement) }; public override void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement) { base.VisitVariableDeclarationStatement(variableDeclarationStatement); + if (!(variableDeclarationStatement.Parent is BlockStatement)) + // We are somewhere weird, like a the ResourceAquisition of a using statement + return; + if (variableDeclarationStatement.Variables.Count > 1) return; @@ -81,7 +86,7 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring var path = GetPath(rootNode, lowestCommonAncestor); var firstLoopStatement = (from node in path - where loopStatements.Contains(node.GetType()) + where blockingStatements.Contains(node.GetType()) select node).FirstOrDefault(); IList possibleDestinationsPath; if (firstLoopStatement == null) { diff --git a/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/VariableDeclaredInWideScopeTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/VariableDeclaredInWideScopeTests.cs index b834dc149c..a3d77036ac 100644 --- a/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/VariableDeclaredInWideScopeTests.cs +++ b/ICSharpCode.NRefactory.Tests/CSharp/CodeIssues/VariableDeclaredInWideScopeTests.cs @@ -243,6 +243,46 @@ class A val = 3; } } +}"; + TestRefactoringContext context; + var issues = GetIssues(new VariableDeclaredInWideScopeIssue(), input, out context); + Assert.AreEqual(0, issues.Count); + } + + [Test] + public void DoesNotSuggestMovingIntoTryCatch() + { + var input = @" +class A +{ + void F() + { + int val = 2; + try { + System.Console.WriteLine(val); + } catch { + throw; + } + } +}"; + TestRefactoringContext context; + var issues = GetIssues(new VariableDeclaredInWideScopeIssue(), input, out context); + Assert.AreEqual(0, issues.Count); + } + + [Test] + public void DoesNotSuggestMovingIntoBodyOfUsing() + { + var input = @" +using System.IO; +class A +{ + void F() + { + using (FileStream fs = new FileStream("""", FileMode.Open, FileAccess.Read, FileShare.Read)) { + fs.Read(null, 0, 0); + } + } }"; TestRefactoringContext context; var issues = GetIssues(new VariableDeclaredInWideScopeIssue(), input, out context);