Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic C# about the "using" keyword

Tags:

c#

asp.net

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)

like image 576
Bill Avatar asked Jul 30 '13 02:07

Bill


People also ask

What is basic C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Which is basic C or C++?

C is the foundational, procedural programming language introduced earlier for system applications and low-level programs. C++ is an Object-oriented programming language with features same as C and additional features like Encapsulation, Inheritance, etc for complex application development.

What are the basic C syntax?

The basic syntax of the C program consists of header, main() function, variable declaration, body, and return type of the program. The header is the first line in the C program with extension . h which contains macro definitions and C functions.


2 Answers

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!

like image 194
Robert Harvey Avatar answered Oct 12 '22 22:10

Robert Harvey


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();
}
like image 32
Felipe Oriani Avatar answered Oct 12 '22 23:10

Felipe Oriani