I've been helping a colleague debug some strange behavior in their code. The following sample illustrates this:
static void Main(string[] args)
{
string answer = Sample();
Console.WriteLine(answer);
}
public static string Sample()
{
string returnValue = "abc";
try
{
return returnValue;
}
catch (Exception)
{
throw;
}
finally
{
returnValue = "def";
}
}
What does this sample return?
You'd think that because of the finally block, it returns "def" but in fact, it returns "abc"? I've stepped through the code and confirmed that the finally block is in fact invoked.
The real answer is that you shouldn't write code like this in the first place but I'm still puzzled as to the behaviour.
Edit: To clarify the flow based on some of the answers.
When you step through the code, the finally is executed before the return.
Duplicate of: What really happens in a try { return x; } finally { x = null; } statement?