Bill
Bill

Reputation: 19338

Basic C# about the "using" keyword

I am a beginner of C# learning.

I realize that using is like import in the C#

But then I have encountered in this situation:

using (con)
{
    con.Open();
    cmd.ExecuteNonQuery();
}

Just curious what's this using doing in here, and what's the different without the using (con)

Upvotes: 5

Views: 4244

Answers (4)

Robert Harvey
Robert Harvey

Reputation: 180938

This form of using (the statement, not the directive) works with the IDisposable interface, to reclaim unmanaged resources.

Unmanaged resources are things like database connections which cannot be simply allowed to be reclaimed by the garbage collector. Rather, they need to be closed in an orderly fashion. When the using code block goes out of scope, the Dispose() method is called on the database connection object, closing the connection and releasing the resource.

As an example, check out the SQLConnection class. Note that it inherits from the DBConnection class, which in turn implements the IDisposable interface. The SQLConnection object implements the Dispose method, which closes the connection when scope leaves the using block.

Note that you can abuse the using statement and IDisposable for fun and profit. ASP.NET MVC uses using to close HTML tags!

Upvotes: 11

Karl Anderson
Karl Anderson

Reputation: 34834

The using block can be applied to any .NET object that implements the IDisposable interface. If you attempt to apply the block against an object that does not, then you will receive a compilation error.

The using block will actually generate a try-finally block around the code within the using block.

The following:

using (con)
{
    con.Open();
    cmd.ExecuteNonQuery();
}

is equivalent to writing:

try
{
    con.Open();
    cmd.ExecuteNonQuery();
}
finally
{
    con.Close();
    con.Dispose();
}

The using block aids is a productivity enhancement that ensures a disposable object is properly cleaned up and, in my opinion, creates code that is easier to read and maintain.

Note: You can nest using blocks, like this:

using(con)
using(cmd)
{

}

The using statement in C# is the equivalent of the Imports statement in VB.NET.

Upvotes: 3

Felipe Oriani
Felipe Oriani

Reputation: 38638

using statement will invoke the Dispose method on the end of the block. The object must implement IDisposable interface to get it work. It works because your object con has a implementation for IDisposable and after this method it is null. I like to implement the using blocks declaring the object, for sample:

using (var con = new SqlConnection("connection string"))
{
    con.Open();

    using(var cmd = con.CreateCommand()) 
    {
       cmd.CommandText = "select count(*) from table";
       result = (int) cmd.ExecuteScalar();
    }

    con.Close();
}

Upvotes: 5

Kevin Anderson
Kevin Anderson

Reputation: 589

According to MSDN

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.

The using statement forces the cleanup of resources without the developer having to explicitly dispose of them or waiting for the Garbage Collector to reclaim the resources.

Upvotes: 3

Related Questions