tig
tig

Reputation: 3483

Mono bug? CS0219 warning when variable is actually used

MonoDevelop (2.10.8) is reporting:

JPGCorruptForm.cs(20,20): Warning CS0219: The variable `myStream' is assigned but its value is never used (CS0219) (JPGCorrupt)

For this function:

    private void toolStripButtonChooseText_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog = new OpenFileDialog();

        openFileDialog.InitialDirectory = ".";
        openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog.FilterIndex = 1;
        openFileDialog.RestoreDirectory = false;

        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            Stop();

            try
            {
                if ((myStream = openFileDialog.OpenFile()) != null)
                {
                    _settings.TextFile = openFileDialog.FileName;
                    CurrentTextFile = _settings.TextFile;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }
    }

This is my frist mono test project and I'm not sure if this kind of thing is normal. It certainly is not fatal, but could get annoying.

Upvotes: 0

Views: 2087

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499770

Well you're assigning a value to the variable, but you're never actually reading from it. In other words, you could easily remove it, just changing the middle expression to:

if (openFileDialog.OpenFile() != null)

Note that your existing code doesn't actually read from the variable even though you might think it does in the comparison to null. It's more like this:

Stream tmp = openFileDialog.OpenFile();
myStream = tmp;
if (tmp != null)

It sounds like you probably should be using it, to close the stream if nothing else... although I'd then declare it as late as possible, like this:

using (Stream myStream = openFileDialog.OpenFile())
{
    if (myStream != null)
    {
        _settings.TextFile = openFileDialog.FileName;
        CurrentTextFile = _settings.TextFile;
    }
}

Here's a simpler example of the same problem, but the way:

using System;

class Test
{
    static void Main()
    {
        string x;

        if ((x = "Hello") != null)
        {
            Console.WriteLine("Yes");
        }
    }
}

Note that with warning level 4 (and possibly lower ones), the Microsoft C# 4 compiler picks up on it too:

Test.cs(7,16): warning CS0219: The variable 'x' is assigned but its value is
        never used

Upvotes: 8

Related Questions