It’s late, but here’s a little humor for ‘ya.
I’ve been noticing recently that I’ve been getting some odd warnings in Visual Studio for variables that are defined and never used. Check out the following screen shot from C# code editor:
Notice how the compiler is warning about isSelected not being used, but as you can see just a few lines down it is in fact being used in an assignment.
At first I thought that maybe the compiler knows something I don’t know and figures the code in the if block never runs, but even if I add the following code:
bool isSelected = false;
if (true)
isSelected = false;
I still get the compiler warning which clearly should serve as an assignment. Then I tried the direct route (which should have been step 1, right? <g>):
bool isSelected = false;
isSelected = true;
and EVEN THAT still gives me the warning. So WTF is going on here?
I changed the name of the variable to isPageSelected. No change.
Finally I tried replacing the static bool value with some dynamic value and that finally got rid of the warning:
bool isPageSelected = false;
isPageSelected = this._Tabs.Count % 1 == 0;
of course that’s non-sensical but it appears that the problem is caused by the compiler getting confused by the constant value assignments to the bool variable.
But then the proverbial light bulb goes off and the hand smacks the forehead: The compiler IS in fact smarter than me! The reason the warning pops up is not because the variable is never assigned, but because it is in fact never used for any sort of comparison in the rest of the method’s code. If I had read the damn message properly in the first place I would have noticed the problem, but no… I got hung up on the first use of the variable.
Technically though the last example I posted really doesn’t change the nature of the behavior and it should also show the same warning, so maybe there is a bug in there after all (yeah I know I’m reaching now).
Been there done that, thank you very much
Anybody else ever done something like this? You are absolutely, 100% sure the compiler is wrong, is out to get you, and you want to – you know do something mean. And then you realize: nope my own fault. As my good pal Peter Bromberg always says – 90% of the time it’s not a problem with the framework or the tool you are working with but rather operator error. Before going off on a ‘bug’ or ‘failure’ take the time to make sure you actually look at it from a few angles.
And yes in case you’re wondering – this post started out as a nag about a problem and a question to ask about why this might be. In this respect blogging can be highly useful to make you re-examine some assumptions and look at problems more closely trying to explain what might be going on, which in this case found my own – ahem failure to read the error message correctly. You win some you lose some…
Other Posts you might also like