Search code examples
c#clrusingtry-finally

Using block: object initialization compiled into try block


In my project I have an object whose constructor can throw. So the code I'm using all across is as follows:

MyObject obj = null;
try
{
    obj = new MyObject();
    obj.DoSomething();
}
finally
{
    if (obj != null)
        obj.Free();
}

As meantioned in Uses of "using" in C#, the code like

using (MyObject obj = new MyObject())
{
    obj.DoSomething();
}

is converted by the .NET CLR to

{
    MyObject obj = new MyObject();
    try
    {
        obj.DoSomething();
    }
    finally
    {
        if (obj != null)
            ((IDisposable)obj).Dispose();
    }
}

The question is: can I somehow make CLR put object's constructor into a try block?


Solution

  • The question is: can I somehow make CLR put object's constructor into a try block?

    No. Or rather, it's pointless to do so, from a resource management perspective. If an exception is thrown by the constructor, then there won't be a reference assigned to obj, so there'll be nothing to call Dispose on.

    It's critical that if a constructor throws an exception, it disposes of any resources it allocated, as the caller won't be able to.