Scope of members inside using statement

I'm confused by the following code and the scope of using statement and its object disposal.

using(DbFactory db = new DbFactory())
{
   Repository repo = new Repository<someobject>(db);
   result = repo.Get(somecondition);
}

In this code what happens after the using block execution will the DbFactory gets disposed?
What will be the scope of repo variable used inside the using statement?
The DbFactory is used by the Repository and it has a member variable which will hold the DbFactory. So will this hold the disposal of DbFactory?

edit1:

Repository repo;
ResultObject result;
using(DbFactory db = new DbFactory())
{
   repo = new Repository<someobject>(db);
   result = repo.Get(somecondition);
}

public class Repository
{
    private _dbFactory;

    public Repository(DbFactory dbFactory)
    {
        _dbFactory = dbFactory;
    }
}

Now will the DbFactory gets disposed after the using statement?

Jon Skeet
people
quotationmark

The scope of the repo variable (in your first case) is the using statement. You can't refer to it outside the using statement, because it's declared in there.

We can't tell the scope of the result variable because you haven't shown its declaration, but it's at least "bigger than the using statement".

What's more interesting is how usable the object that the value of result refers to is after the DbFactory has been disposed. That's implementation-specific, basically... I'd expect that if accessing any result properties requires further database queries (e.g. to get an object referenced by foreign key) then it would fail, but anything that's already fetched should be fine.

As for the timing of disposal - the DbFactory will be disposed at the end of the using statement. That's entirely separate from garbage collection, and presumably the Repository object will still have a reference to it - but it's likely to be useless after the factory has been disposed. So if you call repo.Get(...) after the using statement, you'll probably see an exception, depending on what that code actually does with the factory, and how a disposed factory behaves. Again, disposal isn't garbage collection. It's just calling the Dispose method - the CLR doesn't care about that in any special way.

people

See more on this question at Stackoverflow