Finally will execute, even after return
7 January, 2009 § Leave a Comment
How’s this for weird looking code?
public static void RunSnippet() { var y = testFinally(); if( y == 99 ) { WL("It is 99"); } else { WL("It is 6"); } } public static int? testFinally() { int? x = 99; try { return x; } finally { x = 6; } return x; }
What happens? testFinally will return 99. If you changed the finally block to set x equal to null, the same result will happen. When there is a finally block, the function will not return until after the finally block has finished, regardless of any code following it. The second return statement is never reached. Also, you cannot return from a finally block, since control flow statements cannot be made in a finally block.
The code above was written with SnippetCompiler, a really nice free tool to have at your side when you want to test something out but don’t want to create a new solution in Visual Studio.