Yes, the most appropriate is to do with the using
same. This code is equivalent to this:
{
FileStream fs = new FileStream("abc.txt", FileMode.Create);
try {
// Algum código...
} finally {
if (fs != null)
((IDisposable)fs).Dispose();
}
}
I put in the Github for future reference.
It’s more or less equivalent to try-resource
java.
In some cases it may be more appropriate to do it manually, for example when you need a catch
specific to that resource, or need to do something beyond the dispose()
in the block of finally
. In such cases it is important to make the appropriate provision in finally
, as shown above.
Note that the using
has nothing to do with try-catch
, as asked, and yes to try-finally
.
using is like an automatic Try, any instance that belongs to the interface idisposable it closes automatically at the end, I see that it is only a way to program faster and cleaner.
– Vinicius Fernandes
That’s right, it’s syntactic sugar.
– Maniero