How to convert a try-catch-finally block to using statement in c#?

2020-02-25 c# try-catch using try-catch-finally

Say we create a IDisposable object, and we have a try-catch-finally block

var disposable= CreateIDisposable();
try{
  // do something with the disposable.
}catch(Exception e){
  // do something with the exception
}finally{
  disposable.Dispose();
}

How do I convert this to a using block?

If it were

var disposable= CreateIDisposable();
try{
  // do something with the disposable.
}finally{
  disposable.Dispose();
}

I would convert to

using(var disposable= CreateIDisposable()){
     // do something with the disposable.
}

How would I do this with the catch block?

try{
  using(var disposable= CreateIDisposable()){
     // do something with the disposable.
   }
}catch(Exception e){
  // do something with the exception
}

Answers

You're close. It's the other way around.

In reality, the CLR doesn't have try/catch/finally. It has try/catch, try/finally, and try/filter (that's what it does when the when clause is used on catch). try/catch/finally in C# is just a try/catch within the try block of a try/finally.

So if you expand that and convert the try/finally to using, you get this:

using (var disposable = CreateIDisposable())
{
    try
    {
        // do something with the disposable.
    }
    catch (Exception e)
    {
        // do something with the exception
    }
}

Related