This article will describe what this
statement does and why you should use it often. Note that this article is
discussing the using statement in the context of defining object scope and
disposal,
We also used “using” to include
namespace of classes
using
System;
using-statement:
using ( resource-acquisition ) embedded-statement
When you are using an object that
encapsulates any resource, you have to make sure that when you are done with
the object, the object's Dispose method is called. This can be done more easily using the
using statement in C#. The using statement simplifies the code that you have to
write to create and then finally clean up the object. The using statement
obtains the resource specified, executes the statements and finally calls the Dispose
method of the object to clean up the object.
A using statement is translated into three parts: acquisition,
usage, and disposal. Usage of the resource is implicitly enclosed in a try
statement that includes a finally clause. This finally clause disposes of the resource. If a null
resource is acquired, then no call to Dispose is made, and no exception is thrown.
using System;
public class MyClass : IDisposable
{
private bool disposed;
/// Construction
public
MyClass()
{
}
/// Destructor
~MyClass()
{
this.Dispose(false);
}
/// The dispose method that implements IDisposable.
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// The virtual dispose method that allows
protected virtual void Dispose(bool disposing)
{
if
(!disposed)
{
if
(disposing)
{
//
Dispose managed resources here.
}
//
Dispose unmanaged resources here.
}
disposed = true;
}
public string MyMethod()
{
return "Method in Class";
}
}
Call method
using (MyClass
instance = new MyClass())
{
Response.Write(""+instance.MyMethod());
}
Comments
Post a Comment