DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

C# - Using Statement

12.12.2011
| 2369 views |
  • submit to reddit
        Using statement defines scope of an object/resource. When scope of an object/resource is over then the resource is automatically disposed by the CLR rather then by calling Garbage collector which is not preferred

Lets see through an example, First of all lets declare a class that makes use of using statement. This class must implement IDisposable interface. 

class Student: IDisposable
{
    private String _studentName;
    private int _studentId;

    public String StudentName
    {
        get { return _studentName; }
        set { _studentName = value; }
    }

    public int StudentId
    {
        get { return _studentId; }
        set { _studentId = value; }
    }

    public void Show()
    {
        Console.WriteLine("Student Id:{0}", StudentId);
        Console.WriteLine("Student Name:{0}", StudentName);
    }

    void IDisposable.Dispose()
    {
        Console.WriteLine("Using Statement Scope is over. Student Object is destroyed.");
    }
}

Following is main program:
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Statement Before Using");
        using (Student student = new Student())
        {
            Console.WriteLine("Statement Inside the Using");
            student.StudentName = "Rahul";
            student.StudentId = 123;
            student.Show();
        }
        Console.WriteLine("Statement After Using");
    }
}

Following is Output:
"Statement Before Using" 
"Statement Inside the Using"
"Using Statement Scope is over. Student Object is destroyed."
"Statement After Using"

<a href="http://www.java-forums.org/blogs/eclipse-ide/"><strong>Eclipse IDE</strong></a> and <a href="http://www.java-forums.org/blogs/eclipse/"><strong>Eclipse</strong></a>