Search code examples
c#using-statement

Access Undisposed Resource of a Disposable Object Outside of Using Block


The code below is perfectly legal.

DisposableObject disposableObject;
...
using (disposableObject = new DisposableObject(...))
{
     disposableObject.UseDisposableResource();
}
...
var result = disposableObject.AccessUndisposedResource();

Q Make use of it or stay clear?


Solution

  • There are a couple of norms / expectations involved here:

    1. A disposed object is considered generally finished with and is assumed unusable after disposal (although not compiler-enforced)
    2. using variables are usually declared within the using statement, which exlicitly prevents usage when they have been disposed (again, not compiler-enforced)

    Your code violates both these norms - you have a disposed object which is still expected to be usable, as well as a using block which disposes an external variable which remains in scope after the block. The result? Confusion and hard-to-read-and-maintain code.

    So yes, steer well clear.