Search code examples
c#.netblockusing

what happens when a c# .net using block fails?


If I have a using block, where I create an object (e.g. a FileStream object), and that object fails to create (returns null, throws an exception, etc.), does the code in the block still execute?

using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
    // do stuff with fs here
}
// do more stuff after

If the FileStream constructor were to return null (if the FileStream constructor always returns a valid object, let's just say for sake of argument that it is possible to return null), would the code inside execute? Or would it skip over the "do stuff with fs here" code?


Solution

  • using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
    {
        // do stuff with fs here
    }
    // do more stuff after
    

    is equivalent to:

    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
    try
    {
        // do stuff with fs here
    }
    finally
    {
        if (fs != null)
        {
            ((IDisposable)fs).Dispose();
        }
    }
    // do more stuff after
    

    So to answer your question:

    If the FileStream constructor were to return null (if the FileStream constructor always returns a valid object, let's just say for sake of argument that it is possible to return null), would the code inside execute?

    Yes, it will.

    Obviously everyone familiar with the C# specification knows that a constructor (no matter for which type) can never return null which kind of makes your question a bit unrealistic.