'Handling IDisposable object without the using statement
I'm sure this is an easy question, but what am I supposed to do when handling an IDisposable
object without the using statement?
Solution 1:[1]
All the using
construct does is call on Dispose()
which IDisposable
mandates you implement.
So you can just call it yourself, instead of:
using (IDisposable something = new SomeDisposableClass()) {
...
}
Do:
IDisposable something = new SomeDisposableClass();
try {
...
} finally {
something?.Dispose();
}
Notice the use of the try..finally
which will ensure Dispose()
is called even if there is an exception.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |