What is the use of “using” in C#?

In C#, most of the time we use using a keyword for adding namespaces at the top of the page, so it makes all methods, classes, interfaces, and abstract classes and properties available in the current page like below:

using System;

using System.Text;

Also, we can create the alias of these namespaces by using the = operator like below:

using SYS = System;

And then by using that “SYS” variable and period, we access the classes and methods of the System namespace.

 Another use of the “using” keyword is for creating the object in the using statement like below:


using (SqlConnection conn = new SqlConnection(connectionString))  
            {  
                         SqlCommand cmd = conn.CreateCommand();  

             }

It plays a vital role in improving performance in Garbage Collection.

The using statement ensures that Dispose() is called at the end of the using block execution even if an exception occurred while executing. Dispose() is a method that is present in the IDisposable interface that helps to implement custom Garbage Collection. Like in the above example, while executing the code in the using block if any exception is thrown, it will automatically close the SQL connection. we don’t need to explicitly close it. Even if no exception occurred then also close the connection at the end of the using block because it calls Dispose() method internally.

Post a Comment

0 Comments