Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

"Variable is assigned but its Value is never used" Warning


:P
On this page:

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:

TheVariableIsNeverUsed

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…

Posted in CSharp  Visual Studio  

The Voices of Reason


 

Ran Davidovitz
February 28, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

The funny thing is that i started reading the first few sentences and than started to write you a comment that you are mistaken. than I decided to re-read until the end and I saw your findings which were what I wrote in the comment, the lesson is that its important to read until end before wanting to comment :) and compiler never wrongs :)

Geri Langlois
February 28, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

My embarassments are much greater than this. For instance, has anyone ever made changes to a file and posted to a test site and wondered why the changes were not working (this especially happens when using css ;) ) and then found, after many attempts, that you were posting the wrong file?

Steve from Pleasant Hill
February 28, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

That's what you get for paying attention to warnings and not just the errors page...

Ryan Riley
February 28, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

While this probably misses the point of your post, the warning actually says that the **assigned value** is never used, not the variable. The compiler isn't telling you that you don't need your variable (I think only ReSharper will tell you that); rather, it's telling you that you didn't need to make your initial assignment to false since you change the value before you ever use the variable.

When I first stumbled across this before, I was also annoyed and thought it must be a bug. Then I read the error message again and realized it was right. Apparently, initializing your variables causes warnings. :)

Daniel Crabtree
February 28, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

I noticed this one too. As far as warnings go, it's pretty useful. Hopefully, there will be more warnings for redundant code in the future. I wouldn't mind having warnings for places where code could be improved in other ways too.

Matt Noonan
February 28, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

I used to work with a guy whose Rule #1 was:

"Always believe the error message."

It was amazing how much time and effort is wasted on what I *thought* was the problem, only to go back and re-read the message to find I made an assumption, or mis-read the message, and off I go onto my own tangent that had absolutely nothing to do with the actual problem.

Where as if you follow Rule #1, and internalize the message in your head, you may find yourself grinding the gears less often.

Dave
February 28, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

Not to say that I haven't been there and done that myself but...

I was just talking with a friend of mine about some young developers we know who seem to ALWAYS assume it is the framework, compiler, or whatever..anything but them.

I tend to error on the other end. Or at least I'd like to think I do. For at least the first four hours I assume it is me who is wrong.

Programmers must be the either the craziest people on the planet or the ones with the highest self esteem. Here we are working with an inanimate object who we can't argue with and it tells us all day, "Hey buddy, you did something wrong here."

Andrew Wilson
February 28, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

Rick,

Thank you for this. This interplay exemplifies the point I was trying to get across in my last blog post. (http://pinvoke.wordpress.com/2009/02/28/trust-the-process/)

People are often way to willing to blame something else other than themselves. If you feel like you are working too hard for something... you are probably right. The folks who created the language you program in were not stupid people... but it doesn't mean they get it right all the time. Great faith and great doubt... that's how we learn.

-A

Think Before Coding
March 02, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

Resharper is even smarter at finding unused variable in some complex nested condition scenarios...
It happend to me to spend 10 minutes finding out why a variable was never used... you write a != instead of == or use the wrong variable in a loop / if combination and you're screwed.

But it's very helpfull that those tools can find it... we would never notice it alone before the bug happens in the wild !

dimzon
March 02, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

Actually according Your screenshot the compiler is 100% right!!!
This warning means You WRITE to variable but NEVER READ from it! In your code screenshot you WRITE to it TWICE but NEVER READ...

Rick Strahl
March 02, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

@dimzone - for the screenshot it is. Not for the:

bool isPageSelected = false;
isPageSelected =  this._Tabs.Count % 1 == 0; 


which isn't flagged with the same warning although it probably should.

Silviu
March 02, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

As a programmer you blame the compiler at least once when it's your fault. I thought I was over that after my first few years of programming, but of course I was wrong. Happened a few months ago, took me about 4 hours to find the problem and was going nuts. The problem was that I have added a condition to a breakpoint: "variable = value" instead of "variable == value", I went as far as analyzing msil code of course =)) which revealed nothing because the attribution was done "in the" nop instruction. You can imagine my face when I uncovered the problem.

Richard
March 03, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

This is so familiar, it never ceases to amuse me how often it is you solve a bug by actually reading the error message again.

Phillip Hamlyn
March 03, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

My favourite wasn't a compiler error but was similar in causing me to doubt my sanity;

[StoredProcedureAttribute("sp_SavePerson")]
void SavePerson(PersonEntity person)
{
orm_savePerson(person);
}

Here my ORM used the attribute from the previous call to tell it which stored procedure to use - essentially allowing the business process tier to tell the ORM to use a replacement stored proc. Now instead of simply passing it as a parameter I decided to get clever and have it as an attribute, because then I could do reflection based dependency analysis between the database and the .net tier for future impact analysis of changes. There are on balance much better ways of doing this.

I forgot about inlining. Caused me days of wondering why, when I got into my orm_savePerson function, the call stack didn't have a function with the StoredProcedureAttribute on it. Of course when you're debugging in the IDE inlining doesn't happen - so took me some while to work out what was going wrong.

We live and learn.

Noel McCrory
March 03, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

You should give Resharper a go. It'll highlight this kind of thing to you a lot more clearly.

stm
March 06, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

The strange thing that the compiler not warns us, fails to detect unused variable for such a simple code:

int a = 0;
int b = a; // you won't get any warning

An ms connect entry where ms suggest to use fxcop...

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362970

Ben Amada
March 06, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

The first time I remember seeing this warning, I confused it with its somewhat common "sister" warning:

The variable 'VariableName' is declared but never used.

... when a variable is never assigned a value. It's sort of nice VS gives these warnings for those rare times when you made a logical error or forgot to do something with a variable.

Peter Bromberg
March 07, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

Rick, I see this all the time and never bothered to get into it as deeply as you did. The compiler never lies. If only the government would be so smart!

Rick Strahl
March 07, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

@Peter - yes it's one of those careless errors that are easy to overlook that gets introduced by code refactoring. I have had quite a few of those, but after the 'discovery' of the error of my ways I realized that I can indeed kill most of those or at least reevaluate them.

Events are also an interesting one - if you declare an event but then fail to internally implement any code that actually invokes the event (which in theory could be the task of a subclass - so this isn't entirely as clear cut as the code above).

Re: The compiler never lies. I wouldn't go that far, but most of the time it's a good idea to blame yourself before the compiler however hard on our egos, eh?

Richard Mayes
March 19, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

This highlights the dangers of working late, your brain gets caught up to easily with these "strange" bugs/errors!! Obviously not enough caffeine in your system!! ;)

Steve Trefethen
March 20, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

Having worked on <a href="http://www.codegear.com/delphi">Delphi</a> for years you might be surprised at how many people want compiler warnings turned off simply because of "problems" like this. If the warning isn't produced well, then the issue isn't there! Doh!

Grant
May 13, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

I think that you are really missing the point(s) here.

#1. The compiler is giving a spurious warning message that provides no value whatsoever.

#2. This happens in VS2008 intermittently for no obvious or good reason. Sometimes it generates a warning but other similar code elsewhere does NOT generate a warning. It is inconsistent and thus can and should be considered a bug.

#3. This problem wastes people's time. I like my code to compile without any warnings. This helps me develop reliable high quality code. I have to add useless code to get rid of this warning. This is a waste. There's nothing good or useful about this.

#4. The thinking that the compiler is ALWAYS right is defective I think. Compilers can have bugs. I've encountered a few in my time. Yes, most of the time it is a user/developer problem but what people are really trying to say is that they want to believe 100% in their tools, in this case Visual Studio. That they feel comfortable when they can trust 100% in their tools. That's understandable but a complacent attitude. Especially when dealing with buggy Microsoft libraries and tools. I have found bugs in many Microsoft products. Some that Microsoft will not fix. It seems to be getting worse now. To "change your thinking" that all is right with the world (i.e. Visual Studio) when it's not is unrealistic. Just be realistic and call it a stupid bug or at least a quirk.

- Grant

Rick Strahl
May 13, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

@Grant - uh maybe you didn't bother reading the whole post. The fact is the compiler in this case WAS CORRECT with the warning and the warning has value because it effectively allows you to remove several lines of code from the method.

Yes, it's possible the compiler can be wrong but it is VERY rare and usually well documented if it is. When it comes down to us or the compiler being wrong I think you will find in most cases it'll be us who are wrong.

Of course, if you're arrogant enough to think otherwise - be my guest. A world of pain awaits you :-}

Rick Strahl
May 13, 2009

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

@Steve - yup: Facts do not cease to exist because they are ignored.

Craig
April 28, 2010

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

Banged my head, read your post and then re-read the warning. Got it! Thanks for pointing out the obvious. I missed it.

Jared
May 23, 2010

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

I am extremely new to C#. I received this warning this afternoon. How do I correct it?

young
July 22, 2010

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

I had exactly the same problem. I tried this and that to get rid of the warnings, but nothing worked. And all of sudden, when I build the solution again, the warnings went away. I absolutely changed nothing. It was the exact same code. I don't know what happened. It might be the compiler.

david
January 20, 2011

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

should just enclose them in prama statements

#pragma warning disable 169, 414
private string col2 = null;
private string col3 = null;
#pragma warning restore 169, 414

ivar
April 22, 2016

# re: &quot;Variable is assigned but its Value is never used&quot; Warning

Did the same thing, thank Google. I thought the compiler is smart, then I thought I am smarter.

West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024