The name 'sr' doesn't exist in current context

后端 未结 3 1781
灰色年华
灰色年华 2021-01-22 04:26

I was following example from microsoft site for reading from text file. They say to do it like this:

class Test
{
    public static void Main()
    {
        try         


        
3条回答
  •  不思量自难忘°
    2021-01-22 04:54

    What you described is achieved by putting ; after using statement

    using (StreamReader sr = new StreamReader("TestFile.txt"));
    {
         String line = sr.ReadToEnd();
         Console.WriteLine(line);
    }
    

    Possibly you even didn't notice that and deleted later.

    What's the difference between using(StreamReader) and just StreamReader?

    When you put disposable variable (StreamReader) in using statement it's the same as:

    StreamReader sr = new StreamReader("TestFile.txt");
    try
    {
        String line = sr.ReadToEnd();
        Console.WriteLine(line);
    }
    finally
    {
        // this block will be called even if exception occurs
        if (sr != null)
            sr.Dispose(); // same as sr.Close();
    }
    

    Also if you declare variable in using block, it will be visible only in using block. Thats why ; made your StreamReader non-existing in latter context. If you declare sr before using block, it will be visible later, but stream will be closed.

提交回复
热议问题