C# Language Gotcha: returning the resource which you are disposing


Example

The following is a bad idea because it would dispose the db variable before returning it.

public IDBContext GetDBContext()
{
    using (var db = new DBContext())
    {
        return db;
    }
}

This can also create more subtle mistakes:

public IEnumerable<Person> GetPeople(int age)
{
    using (var db = new DBContext())
    {
        return db.Persons.Where(p => p.Age == age);
    }
}

This looks ok, but the catch is that the LINQ expression evaluation is lazy, and will possibly only be executed later when the underlying DBContext has already been disposed.

So in short the expression isn't evaluated before leaving the using. One possible solution to this problem, which still makes use of using, is to cause the expression to evaluate immediately by calling a method that will enumerate the result. For example ToList(), ToArray(), etc. If you are using the newest version of Entity Framework you could use the async counterparts like ToListAsync() or ToArrayAsync().

Below you find the example in action:

public IEnumerable<Person> GetPeople(int age)
{
    using (var db = new DBContext())
    {
        return db.Persons.Where(p => p.Age == age).ToList();
    }
}

It is important to note, though, that by calling ToList() or ToArray(), the expression will be eagerly evaluated, meaning that all the persons with the specified age will be loaded to memory even if you do not iterate on them.