Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit of "using"

Tags:

c#

using

I want to understand the difference between

public DataTable ExectNonActQuery(string spname, SqlCommand command)
{
    using (DataTable dt = new DataTable())
    {
        cmd = command;
        cmd.Connection = GetConnection();
        cmd.CommandText = spname;
        cmd.CommandType = CommandType.StoredProcedure;
        da.SelectCommand = cmd;
        da.Fill(dt);
        return (dt);
    }
}

and

public DataTable ExectNonActQuery(string spname, SqlCommand command)
{
    DataTable dt = new DataTable();
    cmd = command;
    cmd.Connection = GetConnection();
    cmd.CommandText = spname;
    cmd.CommandType = CommandType.StoredProcedure;
    da.SelectCommand = cmd;
    da.Fill(dt);
    return (dt);
    }
}

I actually want to understand what is the benefit of creating a new object using "using" instead of creating it directly like this

DataTable dt = new DataTable();
like image 528
kashif Avatar asked Apr 28 '12 16:04

kashif


People also ask

What is the benefit of using it?

timely and efficient delivery of products and services. higher sales through better understanding of customer behaviors. cost savings from fewer staff hours and reduced human or machine error. better resource planning through detailed, accurate, and timely financial information.


1 Answers

Your first example is incorrect: using(var ...) ensures that IDisposable.Dispose is called on the variable declared inside using upon exiting. Therefore your first example returns a disposed object, which is almost certainly wrong.

In general, the using block is roughly equivalent to this:

var x = new MyDisposable();
try {
    // Do something with x
} finally {
    x.Dispose();
}

Since this is a very common pattern in C#, a special syntax is provided for your convenience.

like image 56
Sergey Kalinichenko Avatar answered Oct 09 '22 16:10

Sergey Kalinichenko