Should I call Dispose() within a function after Return?

One thing that none of the answers so far have mentioned is that you should dispose the object if Gimme() throws an exception. For example:

MyDisposableObject Gimme() 
{
    MyDisposableObject disposableResult = null;
    try
    {
        disposableResult = ...

        // ... Code to prepare disposableResult

        return disposableResult;
    }
    catch(Exception)
    {
        if (disposableResult != null) disposableResult.Dispose();
        throw;
    }
}

It's the object itself. Don't call Dispose here, even if you reverse the order so that it gets called.


No, you shouldn't. You return a reference to the object, so there is no copy made. In .NET, objects are never copied unless you specifically ask for it.

Also, you can't dispose the object with code like that even if there was a situation where you should. The code after the return statement will never be executed, and you will get a warning about unreachable code.