Search code examples
c#textusingstreamwriter

System.IO.StreamWriter : Why do I have to use keyword "using"


//C#
using (System.IO.StreamWriter writer = 
    new System.IO.StreamWriter("me00.txt", true))
{
    writer.WriteLine("Hey"); //saved 
}
System.IO.StreamWriter writer02 = new System.IO.StreamWriter("me01.txt", true);
writer02.WriteLine("Now hey x2"); //not saved

File me00.txt and me01.txt are created, however only the first file's content gets saved.

me00.txt will have line hey. me01.txt will be an empty txt file; "Now hey x2" is not saved.

What does the keyword "using" do to cause this observation?


Solution

  • You don't have to use "using". It's just a shortcut to keep you from doing even more typing...

    The alternative is to nest the whole thing in a try-finally construct like the following:

     System.IO.StreamWriter writer = null; 
    
     try
     {
         writer = new System.IO.StreamWriter("me00.txt", true);
         writer.WriteLine("Hey");
     }
     finally
     {
         if (writer != null)
            writer.Dispose();
     )
    

    When the writer is disposed, it is also closed, which is the step you're missing. The using presents a tidy way to do all of this compactly.