Using Keyword in C# with Example

Using Keyword in C# with Example
Using Keyword in C# with Example

We have seen how classes like StreamReader and StreamWriter work.  Both the classes contain a method called Close(), which we must call after finishing our job to release any system related resources associated with them.  In both classes, there is one another method called Dispose().  This method completely destroys the object from the memory.  When the object is no longer in use, this method is automatically called by garbage collector.  But instead of relying on garbage collector, you can call this method directly.

Now, while coding, it does happen that developers forget such an important task of releasing system related resources and disposing the object manually.  In this case, using keyword comes into play.  Using keyword is mostly used in 2 situations.  First, we use using keyword on top of our code file to get access to other classes and namespaces residing in another namespace by providing its fully qualified name.  Second, we use using keyword to automatically call Close() and Dispose() methods.  A simple code example for StreamWriter class is given below.

using System;
using System.IO;

namespace Hello
{   

    class Program
    {
        static void Main(string[] args)
        {
            //Using keyword with StreamWriter class.
            using (StreamWriter _sw = new StreamWriter(@"C:\Users\Admin\Desktop\mytext.txt"))
            {
                _sw.WriteLine("John Jackson");
            }            
            
        }
            
    }
}