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
}
usingstatement inside thetryclause, or with the entiretry/catchwithin theusingblock. If no exception is thrown, then the code is nearly identical (theDispose` call happens at the end, though the underlying assembly code will look different). If there is an exception, then, in either case, thecatchclause would execute first and then theDisposecall on the way out the door. I'd call it a toss-up. Of course, yourtry/catch/finallycode is perfectly good as well