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)
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.
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.
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.
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!
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With