Sunday, August 21, 2011

Understanding the 'using' statement in C#

Posted by Rahul Kharde at 10:12 AM

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());
}


If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

 

Popular Posts

Recent Comments

© 2011. All Rights Reserved | Help to understand .Net | Template by Blogger Widgets

Home | About | Top