281

I saw this tip in another question and was wondering if someone could explain to me how on earth this works?

try { return x; } finally { x = null; }

I mean, does the finally clause really execute after the return statement? How thread-unsafe is this code? Can you think of any additional hackery that can be done w.r.t. this try-finally hack?

5 Answers 5

391

The finally statement is executed, but the return value isn't affected. The execution order is:

  1. Code before return statement is executed
  2. Expression in return statement is evaluated
  3. finally block is executed
  4. Result evaluated in step 2 is returned

Here's a short program to demonstrate:

using System;

class Test
{
    static string x;

    static void Main()
    {
        Console.WriteLine(Method());
        Console.WriteLine(x);
    }

    static string Method()
    {
        try
        {
            x = "try";
            return x;
        }
        finally
        {
            x = "finally";
        }
    }
}

This prints "try" (because that's what's returned) and then "finally" because that's the new value of x.

Of course, if we're returning a reference to a mutable object (e.g. a StringBuilder) then any changes made to the object in the finally block will be visible on return - this hasn't affected the return value itself (which is just a reference).

7
  • 1
    I would like to ask, Is there any option in visual studio to see the generated Intermediate language(IL) for written C# code at the time of execution....
    – Glory Raj
    Dec 30, 2011 at 13:29
  • 5
    @Nick: That's not a change to the object - that's a change to the variable. It doesn't affect the object that the previous value of the variable referred to at all. So no, it's not an exception.
    – Jon Skeet
    Sep 10, 2013 at 5:43
  • 3
    @Skeet Does that mean "return statement returns a copy"? Mar 6, 2014 at 11:45
  • 5
    @prabhakaran: Well it evaluates the expression at the point of the return statement, and that value will be returned. The expression is not evaluated as control leaves the method.
    – Jon Skeet
    Mar 6, 2014 at 11:57
  • 2
    @jeromej: I really don't think it's necessary - if someone decides to stop reading an answer half way through, I think that's on them.
    – Jon Skeet
    Jun 2, 2022 at 11:02
246

No - at the IL level you can't return from inside an exception-handled block. It essentially stores it in a variable and returns afterwards

i.e. similar to:

int tmp;
try {
  tmp = ...
} finally {
  ...
}
return tmp;

for example (using reflector):

static int Test() {
    try {
        return SomeNumber();
    } finally {
        Foo();
    }
}

compiles to:

.method private hidebysig static int32 Test() cil managed
{
    .maxstack 1
    .locals init (
        [0] int32 CS$1$0000)
    L_0000: call int32 Program::SomeNumber()
    L_0005: stloc.0 
    L_0006: leave.s L_000e
    L_0008: call void Program::Foo()
    L_000d: endfinally 
    L_000e: ldloc.0 
    L_000f: ret 
    .try L_0000 to L_0008 finally handler L_0008 to L_000e
}

This basically declares a local variable (CS$1$0000), places the value into the variable (inside the handled block), then after exiting the block loads the variable, then returns it. Reflector renders this as:

private static int Test()
{
    int CS$1$0000;
    try
    {
        CS$1$0000 = SomeNumber();
    }
    finally
    {
        Foo();
    }
    return CS$1$0000;
}
2
  • 10
    Isn't this exactly what ocdedio said: the finally is executed after the calculation of the return value and before really returning from the funczion???
    – mmmmmmmm
    Jan 7, 2009 at 20:04
  • 1
    "exception-handled block" I think this scenario has nothing to do with exceptions and exception handling. This is about how .NET implements the finally resource guard construct. Oct 30, 2015 at 12:35
22

The finally clause executes after the return statement but before actually returning from the function. It has little to do with thread safety, I think. It is not a hack - the finally is guaranteed to always run no matter what you do in your try block or your catch block.

13

Adding onto the answers given by Marc Gravell and Jon Skeet, it is important to note objects and other reference types behave similarly when returned but do have some differences.

The "What" that gets returned follows the same logic as simple types:

class Test {
    public static Exception AnException() {
        Exception ex = new Exception("Me");
        try {
            return ex;
        } finally {
            // Reference unchanged, Local variable changed
            ex = new Exception("Not Me");
        }
    }
}

The reference that is being returned has already been evaluated before the local variable is assigned a new reference in the finally block.

The execution is essentially:

class Test {
    public static Exception AnException() {
        Exception ex = new Exception("Me");
        Exception CS$1$0000 = null;
        try {
            CS$1$0000 = ex;
        } finally {
            // Reference unchanged, Local variable changed
            ex = new Exception("Not Me");
        }
        return CS$1$0000;
    }
}

The difference is it would still be possible to modify mutable types using the properties/methods of the object which can result in unexpected behaviors if you are not careful.

class Test2 {
    public static System.IO.MemoryStream BadStream(byte[] buffer) {
        System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);
        try {
            return ms;
        } finally {
            // Reference unchanged, Referenced Object changed
            ms.Dispose();
        }
    }
}

A second thing to consider about try-return-finally is that parameters passed "by reference" can still be modified after the return. Only the return value has been evaluated and is stored in a temporary variable waiting to be returned, any other variables are still modified the normal way. The contract of an out parameter can even go unfulfilled until the finally block this way.

class ByRefTests {
    public static int One(out int i) {
        try {
            i = 1;
            return i;
        } finally {
            // Return value unchanged, Store new value referenced variable
            i = 1000;
        }
    }

    public static int Two(ref int i) {
        try {
            i = 2;
            return i;
        } finally {
            // Return value unchanged, Store new value referenced variable
            i = 2000;
        }
    }

    public static int Three(out int i) {
        try {
            return 3;
        } finally {
            // This is not a compile error!
            // Return value unchanged, Store new value referenced variable
            i = 3000;
        }
    }
}

Like any other flow construct "try-return-finally" has its place and can allow for cleaner looking code than writing the structure it actually compiles to. But it must be used carefully to avoid gotcha's.

4

If x is a local variable, I don't see the point, as x will be effectively set to null anyway when the method is exited and the value of the return value is not null (since it was placed in the register before the call to set x to null).

I can only see doing this happening if you want to guarantee the change of the value of a field upon return (and after the return value is determined).

3
  • Unless the local variable is also captured by a delegate :)
    – Jon Skeet
    Jan 7, 2009 at 19:54
  • Then there is a closure, and the object can't be garbage collected, because there is still a reference.
    – recursive
    Jan 7, 2009 at 20:05
  • But I still don't see why you would use a local var in a delegate unless you intended to use its value.
    – recursive
    Jan 7, 2009 at 20:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.