What is the importance of the Using Statement in Microsoft Dot Net Programming Code?
One of the most important things in managed languages is the automatic management of the application objects in memory using Runtime Environment named Garbage Collector (GC) which is responsible for releasing unused objects from memory and returning their locations in memory to system. But the more the GC runs, the more the application becomes slower since the process is not smooth and fast especially where unmanaged code is used which is a hard slow process done by the GC since GCdoes not have enough information about codes and objects from outside its environment.
Microsoft adds IDisposable interface with an implementation pattern to be used by developers for any unmanaged code to allow unmanaged codememory release by calling the Dispose method from the IDisposable interface without relying on the GC to do the process which leads to very smaller memory and much higher performance during application life cycle by lowering the GC need to release unmanaged code and the number of times it needs to run.
C# IDisposable Design Pattern:
using System;
class BaseClass : IDisposable
{
// Flag: Has Dispose already been called?
bool disposed = false;
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing) {
// Free any other managed objects here.
//
}
// Free any unmanaged objects here.
//
disposed = true;
}
~BaseClass()
{
Dispose(false);
}
}
Using Statement, Microsoft Definition:
Provides a convenient syntax that ensures the correct use of IDisposableobjects.
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way; it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
C# Using Statement Example:
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
Examples of IDisposable objects:
SqlConnection, DataSet, DataTable, SqlDataReader, Font, DataView, SqlCommand, SqlDataAdapter … etc.
Dot Net Code Elixir Number 0003:
https://goo.gl/KuOsjO
Draft 0003 Dot Net Code Elixir E-Book:
https://goo.gl/HrygWP