Using Statement

Defines the scope for the existence of an object.
Although the CLR automatically releases memory when it performs garbage collection it is best practice to release resources as quickly as possible.
This statement allows you to specify when an object should be released.
The object provided to the using statement must implement the IDisposable interface
This interface provides the Dispose method which should release the objects resources.


If you always want an object disposed of after performing some operations you should use the Using statement

using (SomeObject myobject = new SomeObject();) 
{
   myobject.DoSomething();
}

is equivalent to

SomeObject myobject = new SomeObject(); 
try
{
   myobject.DoSomething();
}
finally
{
   myobject.Dispose();
}


The using statement can be exited when the end of the statement is reached or an exception is thrown and control leaves before the end.
The object can be declared in the using statement or before


Font font = new Font("Arial", 10.0f); 
using (font)
{
}

using (Font font = new Font("Arial", 10.0f)) 
{
}


Multiple Objects

You can use multiple objects but they must be declared in the using statement.



Using Directive

The using statement is not to be confused with the Using Directive



© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrev