What about using constructs in C #

I see it:

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

All I am trying to find does not explain what it does, and instead gives me information about namespaces.

+3
source share
5 answers

You want to check the documentation for using statement (instead of using using directive, which refers to namespaces).

This basically means that the block is converted to the try/ block finally, and sw.Dispose()is called in the finally block (with a suitable invalidation check).

using , IDisposable - , .

:

  • :

    using (Stream input = File.OpenRead("input.txt"),
           output = File.OpenWrite("output.txt"))
    {
        // Stuff
    }
    
  • :

    // For some suitable type returning a lock token etc
    using (padlock.Acquire())
    {
        // Stuff
    }
    
  • ;

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

, . ,

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

8.13 .

+5
0
source

Source: https://habr.com/ru/post/1739196/


All Articles