Search code examples
c#filestreamreadernullable-reference-types

C# StreamReader.Readline() in while loop giving me nullable to non nullable warning


So my question is i'm getting a warning from visual studio stating that

"null literal or possible null value to non-nullable type"

and the code works and executes as expected, however i still receive this warning and i'm unsure how to resolve the issue.

i have declared StreamReader as a private property at the start. If someone could point me into a direction or suggest an improvement to prevent this warning it would be appreciated, i have attached the relevant code below:

private StreamReader? streamReader;
public Form1()
        {
            InitializeComponent();

            CreateFiles();
            ReadFiles();
        }

private void ReadFiles()
    {
        streamReader = File.OpenText(path + _productTypeFile);
        string line = "";
        if (streamReader == null)
        {
            throw new Exception("An error occured with stream reader");
        }
        while ((line = streamReader.ReadLine()) != null)
        {
            currentProdTypeListBox.Items.Add(line);
        }
        if (streamReader.ReadLine() == null) streamReader.Close();
    }

The line below is where the warning is coming from:

while ((line = streamReader.ReadLine()) != null)

Solution

  • Change the function to this:

    private void ReadFiles()
    {
       string path = "your path";
       using StreamReader streamReader = File.OpenText(path );
    
       if (streamReader == null)
          throw new Exception("An error occured with stream reader");
       var line = "";
       while (( line = streamReader.ReadLine()) != null)
       {
        currentProdTypeListBox.Items.Add(line);
       }
       streamReader.Close();
    }