C# and ‘using’

A really useful keyword in the c# language is:-

using (declaration)
{
…Code here
}

I use it quite often, especially when setting up database connections, as these are often pooled. The great thing about the using keyword is thaT once the final brace is run in the code the object destroys itself. When I have to make connections that might take me to different servers I use using to make the connection, run the SQL and close the connection. Exiting the final brace clears everything and I am ready to move on to the next connection.

The using keyword will clear all resources as it exits, so if I forget a .close() or want to have several consecutive connections this little helper makes life clean and simple; the other beauty of it is that you can see in the code everthing you are doing within that one session.
It is very, very useful.

Give it a go and see!

Comments are closed.