using keyword is basically a
finally block, without a
catch , where
IDisposable.Dispose() is called in the
Using block defines a scope, outside of which an object or objects will be disposed.
Use using keyword for the objects that hold any resources other than managed memory. For Example like files, sockets, database connections, or even GDI drawing handles.
We should be using "using" whenever the class implements IDisposable. So use of using keyword will always help to avoid Garbage Collection call or explicitly calling garbage collector to
For exampleusing(Dataset ds = new Dataset())
We do not need to worry about destroying objects once the job is done. Garbage Collector will take care of it.
using(ClassName x = new ClassName())
...use x here...
Another Example while working with database objects :
using ( SqlConnection connection = new SqlConnection(connectionString) )
SqlCommand cmd = new SqlCommand(commandString, connection);
using (SqlDataReader reader = cmd.ExecuteReader())
But normally we use try ,catch and dispose objects explicitly in Finally. Why to do this when we have the job that will be done by CLR through GC with the help of using keyword. 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. Multiple Objects can be used with using statement as
using (Furniture chair = new Furniture(300, 400),
table = new Furniture(20, 100))
// Use chair and table.
It is very important to know when to use what and implement best practices to achieve for performance , reliability