C# Conundrum – Try/Fail/Return

What do you think this does?

The finally block is guaranteed to run after the try block, but….and it’s a BIG but, hasn’t it already returned a value?

First, have a think about what you think will happen, then try typing/copying it into Visual Studio to see what it makes of it. Done that? Was you right?

To understand why this won’t compile (and let’s hope that isn’t a surprise now that you’ve been told!), let’s take a look at what the C# Specification has to say about it in section 8.9.4:

It is a compile-time error for a return statement to occur in a finally block.

If you think it through, it does seem to make sense. Once a value is returned, how can you return another? Where would it go?

OK, but what about this then?

Will anything be printed to the screen?

Yes, and we can see why by looking at section 8.10 of the specification:

The statements of a finally block are always executed when control leaves a try statement. This is true whether the control transfer occurs as a result of normal execution, as a result of executing a break, continue, goto, or return statement, or as a result of propagating an exception out of the try statement.

Output:

So, there you have it 🙂 Not all returns are instantaneous!

twittergoogle_plusredditpinteresttumblrmail

Written by Stephen Moon
email: stephen at logicalmoon.com
www: https://www.logicalmoon.com


This entry was posted in: c#. Bookmark the ➜ permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *