Carlo
Carlo

Reputation: 151

c# dispose - is this correct?

Is this correct way of disposing and using

public partial class Form1 : Form
{
    winappContext _context;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        using (_context = new winappContext())
        {
            _context = new winappContext();
            var query = from c in _context.Customers
                        orderby c.CustomerName
                        select c;

            this.customerBindingSource.DataSource = query.ToList();
        }
....

or I need to call _context.Dispose() onFormClosing

Thanks

Upvotes: 0

Views: 132

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1500055

Neither. Assuming you don't need _context to be a field (there's no indication that you do) you should make it a local variable:

private void Form1_Load(object sender, EventArgs e)
{
    using (winappContext _context = new winappContext())
    {
        var query = from c in _context.Customers
                    orderby c.CustomerName
                    select c;

        this.customerBindingSource.DataSource = query.ToList();
    }
}

In general, it's a pain to have fields which implement IDisposable - it's much cleaner if you can just dispose of resources within the same methods that they're acquired.

Also note that your original code creates two contexts:

using (_context = new winappContext())
{
    _context = new winappContext();
    ...
}

That means the first one was being disposed of automatically, but the second wasn't. If you try to do this in a using statement where you declare the variable as part of the introductory part of the statement, the variable is read-only so you can't make this mistake.

(You should also rename your winappContext class to follow .NET naming conventions.)

Upvotes: 12

TylerD87
TylerD87

Reputation: 1618

The two examples you have given are equivalent. The compiler goes away and converts your using command to a try...finally with the Dispose() command called in the finally brace.

Upvotes: 0

Ruben Giaquinto
Ruben Giaquinto

Reputation: 390

You don't need to call the dispose object.

The Using statement automatically release the resource and avoid you to call the Dispose method.

Upvotes: 0

wondra
wondra

Reputation: 3573

The "using" mark the disposable object in () to be disposed after {} ends. so no. Dont dispose, its done for you.

Upvotes: 0

Related Questions