Question

If MyClass implements IDisposable interface, will the both given snippets disposes MyClass object correctly? and which method is preferable over the other?

Code 1

public MyModel MethodOne()
{
    using (MyClass myClass = new MyClass())
    {
        var myModel = new MyModel();
        myModel.MyModelData = myClass.GetData();

        return myModel;
    }
}

Code 2

public MyModel MethodTwo()
{
    var myData = new MyData();

    using (MyClass myClass = new MyClass())
    {
        myData = myClass.GetData();
    }

    var myModel = new MyModel();
    myModel.MyModelData = myData;

    return myModel;
}
Was it helpful?

Solution

It is the same: the object will be disposed in both way.

the using statement is translated by the compiler as a try block which calls Dispose in a finally block.

finally is guaranteed to execute after the try block has finished execution, regardless of its execution path.

Dispose is guaranteed to be called, no matter what.

Reference MSDN

As a style and best practice IMHO it is better to dispose an object as soon as it is not needed anymore because you will free resources earlier and because if Dispose throw an exception you will have your method return anything. and it will be easier to debug.

Update

As KrisVandermotten pointed out there are some cases where the finally block will not execute.

  • Environment.FailFast
  • the Uncatchable execeptions
  • Power Failure

OTHER TIPS

using is translated to try with finally block. Your code

using (MyClass myClass= new MyClass())
{
    myData = myClass.GetData();
}

Is the same as

MyClass myClass= new MyClass();
try
{
    myData = myClass.GetData();
}
finally
{
    if (myClass != null)
        ((IDisposable)myClass).Dispose();
}

As for which method is preferable, both solutions will work fine. The second one disposes of the object earlier and for that reason is preferable, in many cases. There's no need to hold on to objects, especially if they use external resources.

There are exceptions to that, though. You may want to or need to hold on to an object for longer to achieve your objective, e.g. when using a transaction scope. Also, sometimes the objects derived from the disposable object (as in your case) may become invalid if the originating object is disposed.

In both cases, you can rely on the fact that, if an object of MyClass was constructed and the method completes, the object is also disposed.

In the latter case, the object is constructed later than in the first case, and it is disposed earlier than in the first case, but in both cases it will be disposed.

Which is better? Assuming that a disposable object somehow holds on to something that needs to be freed, and that this holding on to it is expensive, all else being equal, the better approach would be the second.

So why the two caveats above?

"if an object of MyClass was constructed"

In the second case, it is possible that the call to new MyData() throws an exception, and the MyClass object construction is not even attempted. In the first case, constructing this object is the first thing that happens. It may fail, but it will be tried. It may fail in the second case as well of course. And if it fails, there is nothing to be disposed.

"and the method completes"

Nothing will be disposed if you lose power before the dispose can be executed, and there are a few other pathological cases where execution of a finally block is not guaranteed.

IMHO the first version is more concise and therefore better, since the extra time taken before disposing is likely to be negligible. It typically doesn't take long to construct a couple of objects and set a property.

Only if there were a call to "myModel.DoSomethingThaTakesALongTime()" would I consider using the second version.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top