C# Conundrum - Try/Fail/Return

What do you think this does?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Return Value = {0}", DummyFunction());
}

static int DummyFunction()
{
try
{
return 1;
}
finally
{
return 2;
}
}
}

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Return Value = {0}", DummyFunction());
}

static int DummyFunction()
{
try
{
return 1;
}
finally
{
Console.WriteLine("Hello");
}
}
}

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
Return Value = 1

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