Search code examples
c#garbage-collectiondatacontextusing

Can I declare a context outside using() and still get Dispose() to be called?


I have a class FooDataContext, that implements Linq's DataContext, that have Dispose()..

public partial class FooDataContext : System.Data.Linq.DataContext {...}

I know I should declare fooDataContext inside a using(<here>){}, so Dispose() is called for me, like this

public void Bar()
{
    using (var fooDataContext = new FooDataContext(ConnStr))
    { // some code
    }
}

But I don't know if this is just as good. Is it? What happen behind the scene?

public void Baz()
{
    var fooDataContext = new FooDataContext(ConnStr);
    using (fooDataContext)
    { // some code
    }
}

Solution

  • The latter will basically behave the same way, with one downside: you can still refer to fooDataContext outside the using statement, despite the fact that it's then disposed. That's rarely a good idea.

    So yes, it's entirely legal to use the second snippet - but you should prefer the first version in almost all cases.