I know that the following statement is useful for garbage collection. Effectively it must be the same as Try/Catch/finally. If I use it for the sql connection should i also nest a further ‘using’ statement for a sql adapter? And then a further nested using for the DataSet?
using()
{
}
A further addition to the question is if I want to use the same connection across several methods then is it best practice to have ‘Using()’ in each of the methods, or can I just create this connection object once?
Yes, you should use the
usingstatement to dispose everything that implementsIDisposable. Theusingstatement is not really about garbage collection, it’s about resources (other than memory). Both DataSet and SqlDataAdapter are instances ofIDisposable.The
usingblock means that you guarantee that the resources that the object holds are disposed in a timely, deterministic manner. Withoutusing, there is no guarantee when these resources will be freed. This can lead to resource leaks, such as running out of file handles.