What are the uses of “using” in C#?

后端 未结 29 2894
有刺的猬
有刺的猬 2020-11-21 07:31

User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of

29条回答
  •  盖世英雄少女心
    2020-11-21 07:49

    I've used it a lot in the past to work with input and output streams. You can nest them nicely and it takes away a lot of the potential problems you usually run into (by automatically calling dispose). For example:

            using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
            {
                using (BufferedStream bs = new BufferedStream(fs))
                {
                    using (System.IO.StreamReader sr = new StreamReader(bs))
                    {
                        string output = sr.ReadToEnd();
                    }
                }
            }
    

提交回复
热议问题