diff --git a/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertIfToSwitchAction.cs b/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertIfToSwitchAction.cs index a7ac1bb7c4..a7410fcd02 100644 --- a/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertIfToSwitchAction.cs +++ b/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertIfToSwitchAction.cs @@ -174,22 +174,16 @@ namespace ICSharpCode.NRefactory.CSharp.Refactoring static void CollectSwitchSectionStatements (AstNodeCollection result, RefactoringContext context, Statement statement) { - BlockStatement blockStatement; - if (statement is BlockStatement) - blockStatement = (BlockStatement)statement.Clone (); + BlockStatement blockStatement = statement as BlockStatement; + if (blockStatement != null) + result.AddRange(blockStatement.Statements.Select(s => s.Clone())); else - blockStatement = new BlockStatement { statement.Clone () }; - - var breackStatement = new BreakStatement (); - blockStatement.Add (breackStatement); - // check if break is needed - var reachabilityAnalysis = context.CreateReachabilityAnalysis (blockStatement); - if (!reachabilityAnalysis.IsReachable (breackStatement)) - blockStatement.Statements.Remove (breackStatement); - - var statements = blockStatement.Statements.ToArray (); - blockStatement.Statements.Clear (); - result.AddRange (statements); + result.Add(statement.Clone()); + + // add 'break;' at end if necessary + var reachabilityAnalysis = context.CreateReachabilityAnalysis (statement); + if (reachabilityAnalysis.IsEndpointReachable(statement)) + result.Add(new BreakStatement()); } } } diff --git a/ICSharpCode.NRefactory.Tests/CSharp/CodeActions/ConvertIfToSwtichTests.cs b/ICSharpCode.NRefactory.Tests/CSharp/CodeActions/ConvertIfToSwtichTests.cs index 34167d4600..f2b32ed13c 100644 --- a/ICSharpCode.NRefactory.Tests/CSharp/CodeActions/ConvertIfToSwtichTests.cs +++ b/ICSharpCode.NRefactory.Tests/CSharp/CodeActions/ConvertIfToSwtichTests.cs @@ -30,7 +30,7 @@ using NUnit.Framework; namespace ICSharpCode.NRefactory.CSharp.CodeActions { [TestFixture] - public class ConvertIfToSwtichTests : ContextActionTestBase + public class ConvertIfToSwitchTests : ContextActionTestBase { [Test] @@ -467,5 +467,40 @@ class TestClass }"); } + [Test] + public void TestNestedIf () + { + Test (@" +class TestClass +{ + void TestMethod (int a) + { + int b; + $if (a == 0) { + if (b == 0) + return; + } else if (a == 2 || a == 3) { + b = 2; + } + } +}", @" +class TestClass +{ + void TestMethod (int a) + { + int b; + switch (a) { + case 0: + if (b == 0) + return; + break; + case 2: + case 3: + b = 2; + break; + } + } +}"); + } } }