Suppose I have a class DisposableObject which implements IDisposable. There is a risk it can throw an exception from any constructor and from the DoStuff function. I want to do something like this, so that no matter what happens, the object is disposed properly:
edit: I would like to avoid duplicate code, so a using inside each if/else block is not desirable (the code is a lot more complex than here)
edit2: Yes the try/finally error was wrong, changed it to use of unassigned local variable.
using (DisposableObject worker)
{
if(/*condition*/)
worker = new DisposableObject(/*args*/)
else
worker = new DisposableObject(/*other args*/)
worker.DoStuff();
}
But I can't, because the compiler says I must provide an initializer in the using statement. I can't use try/finally either:
DisposableObject worker;
try
{
if(/*condition*/)
worker = new DisposableObject(/*args*/)
else
worker = new DisposableObject(/*other args*/)
worker.DoStuff();
}
finally
{
worker.Dispose();
}
The compiler says use of unassigned local variable 'worker'.
So what can I do? Obviously I can't simply go like this...
DisposableObject worker;
if (/*condition*/)
worker = new DisposableObject(/*args*/)
else
worker = new DisposableObject(/*other args*/)
worker.DoStuff();
worker.Dispose();
Because I can't be sure the Dispose() function is ever reached.
tryblock). What's your actual code?catch { }in there and see if the problem persists.DisposableObject worker = null;instantiation outside the try/finally