Frequently, we don't really care what the exception is, but if it is thrown we want to finalise operations e.g. close the database connection or files. This is where using
comes in. using
keyword allows to make code a little bit more readable by omitting try-catch-finally clause. Instead, your object should implement IDisposable
interface and the Dispose()
method will be called when either the operation succeeds or there is an exception i.e. the finally clause.
1 2 3 4 5 6 7 8 9 |
MyEntities db; try { db = new MyEntities(); db.SomeOperation(); } catch (Exception e) { } finally { db.Dispose(); } |
Instead, we can use a much neater way of expressing the same logic.
1 2 3 4 |
using(MyEntities db = new MyEntites()) { db.SomeOperation(); } |
db.Dispose()
will be called automatically on the exit from the using
block.