What about the construction of use in c #

advertisements

I see this:

using (StreamWriter sw = new StreamWriter("file.txt"))
{
     // d0 w0rk s0n
}

Everything I try to find info on is does not explain what this doing, and instead gives me stuff about namespaces.


You want to check out documentation for the using statement (instead of the using directive which is about namespaces).

Basically it means that the block is transformed into a try/finally block, and sw.Dispose() gets called in the finally block (with a suitable nullity check).

You can use a using statement wherever you deal with a type implementing IDisposable - and usually you should use it for any disposable object you take responsibility for.

A few interesting bits about the syntax:

  • You can acquire multiple resources in one statement:

    using (Stream input = File.OpenRead("input.txt"),
           output = File.OpenWrite("output.txt"))
    {
        // Stuff
    }
    
    
  • You don't have to assign to a variable:

    // For some suitable type returning a lock token etc
    using (padlock.Acquire())
    {
        // Stuff
    }
    
    
  • You can nest them without braces; handy for avoiding indentation

    using (TextReader reader = File.OpenText("input.txt"))
    using (TextWriter writer = File.CreateText("output.txt"))
    {
        // Stuff
    }