Will a using clause close this stream?

后端 未结 5 1257
难免孤独
难免孤独 2020-12-20 10:55

I\'ve apparently worked myself into a bad coding habit. Here is an example of the code I\'ve been writing:

using(StreamReader sr = new StreamReader(File.Open         


        
5条回答
  •  旧时难觅i
    2020-12-20 11:30

    Note - your using blocks do not need to be nested in their own blocks - they can be sequential, as in:

    using(FileStream fs = File.Open("somefile.txt", FileMode.Open))
    using(StreamReader sr = new StreamReader(fs))
    {
        //read file
    }
    

    The order of disposal in this case is still the same as the nested blocks (ie, the StreamReader will still dispose before the FileStream in this case).

提交回复
热议问题