C# Conundrum - Try/Fail/Return
What do you think this does?
1 | class Program |
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 afinally
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?
1 | class Program |
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:
Hello |
So, there you have it :-) Not all returns are instantaneous!
Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com