简体   繁体   中英

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?

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.

No you can not do that as, this is using and it works in that way. You have to write the code you need by yourself

Worth mentioning that having exception in ctor of the type, is not a good idea at all, so may be , if this is possible move the code that can potentially raise an exception to another place. It's better to have one more method and constrain consumer of your type to call that explicitly in order to achieve something and having control over situation, then having situations like you describe.

In general, use ctor only for construction of the instance of a given type and initialization of internal values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM