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;
}
It is the same: the object will be disposed in both way.
the
usingstatement is translated by the compiler as a try block which callsDisposein a finally block.finallyis 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.