Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

c# - Why is no warning given for this unused variable?

When compiling the following program in VS2010, VS2008 or MonoDevelop on Windows, I get warning CS0219, "The variable 'y' is assigned but its value is never used".

namespace Problem
{
    public class Program
    {        
        private static void Main(string[] args)
        {
            object x = new object();
            int y = 0;
        }
    }
}

Why is there no warning for x when compiling in Visual Studio?

Interestingly, I do get CS0219 warnings for x and y when compiling in MonoDevelop on Mac OS X.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It turns out that this warning is suppressed when the right-hand-side of the assignment operation is not a compile-time constant.

A since-deleted post on Microsoft's Visual Studio feedback site explained that it's because they had lots of complaints from people who were assigning variables purely so they could see what a method call returned during debugging, and found the warning irritating:

The suppression of the "assigned but never used" warning in this case was motivated by feedback from users who do this:

int Blah(){
    // blah
    BlahBlah(x, y, z)
    // blah
    // blah
}

"Hey," says the user while debugging, "I wonder what BlahBlah is returning?" But there is no easy way to examine the return value in the debugger, so users very frequently do this:

int Blah()
{
    // blah
    int temp = BlahBlah(x, y, z)
    // blah
    // blah
}

and then use the locals or watch window to examine temp. The temp is never used anywhere else in the function, so it produced an irritating "assigned but not read" warning.

I think this is a bit of a shame since:

  1. I actually find these warnings helpful when they are given in MonoDevelop.
  2. Anyone can suppress the warning themselves (admittedly they'd also be suppressing the ones for unused compile-time constant assignments - maybe there should be a separate warning for that?).

Anyway, I understand that you can't please everyone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...