What is the advantage of "use",

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);
    }
}

In fact, I want to understand the advantage of creating a new object using "use" instead of directly creating it

DataTable dt = new DataTable();
+5
source share
6 answers

using ensures that the object is located at the end of the using statement

you could call .Dispose () manually, but with usingit will be deleted even if you selected an exception

And you are protected from your own mistakes, for example, you forget to call. Set or reassign the variable before calling Dispose on it.

All this in the documentation:

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Edit: , dasblinkenlight , -

DataTable, DataSet DataView , , DataTable IDisposable. , DataTable.Dispose() ( ), , .

. Dispose() DataSet DataTable?

, , , .

, , IDisposables Statement , . ( , , ).

+11

: using(var ...) , , using, IDisposable.Dispose. , .

using :

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

#, .

+16
using (DataTable dt = new DataTable())

DataTable dt = new DataTable();
try
{
}
finally 
{
    if(dt != null)
        dt.Dispose()
}

, - , . , , DataTable

+4

msdn,

, .

/ , . . , , , using ( ).

- SQL-. , Close. , statmenet, . .

CLR usaully , CLR . using, /, .

+1

- using.

using , IDisposable.

using (DataTable dt = new DataTable()) { }

DataTable dt = new DataTable() dt, using.

DataTable dt = new DataTable();
using (dt) { }

, , , , , , .

+1

IDisposable, , .

This is really very interesting, because the compiler itself translates the use of a try..Finally expression, just as it translates constants into their values. So the usage and try..finally behavior is the same at runtime :).

Use the following link for a deeper understanding: http://www.codeproject.com/Articles/6564/Understanding-the-using-statement-in-C

Hope this helps.

+1
source

All Articles