开发者

What about the using construct in c#

开发者 https://www.devze.com 2022-12-25 07:43 出处:网络
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 开发者

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
    }
    


The using construct is essentially a syntactic wrapper around automatically calling dispose on the object within the using. For example your above code roughly translates into the following

StreamWriter sw = new StreamWriter("file.text");
try {
  // do work 
} finally {
  if ( sw != null ) {
    sw.Dispose();
  }
}


Your question is answered by section 8.13 of the specification.


Here you go: http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Basically, it automatically calls the Dispose member of an IDisposable interface at the end of the using scope.


check this Using statement

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号