User kokos answered the wonderful Hidden Features of C# question by mentioning the using
keyword. Can you elaborate on that? What are the uses of
Just adding a little something that I was surprised did not come up. The most interesting feature of using (in my opinion) is that no mater how you exit the using block, it will always dispose the object. This includes returns and exceptions.
using (var db = new DbContext())
{
if(db.State == State.Closed) throw new Exception("Database connection is closed.");
return db.Something.ToList();
}
It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.