Inconsistent warnings for unused variables

P

proxyuser

If I write simply this with no other references to i, I get a compiler
warning.

int i = 1;

The variable 'i' is assigned but its value is never used.

This does not give an error:
string s = String.Empty;

This does:
string s = "";

This does:
object o;

This does not:
object o = new object();

This does:
bool b = false;

Anyone know what the deal is?
 
P

proxyuser

Peter Duniho said:
Did you mean:

object o = null;

?

The statement you showed gives a somewhat different warning than the rest
of the statements.

You're right, but I was essentially grouping that warning in as well.
All of the cases that emit a warning involve constant expressions. All
the cases that don't involve expressions evaluated at run-time.

That's an interesting observation, but I'm not sure what it means. Does the
compiler let it go because it thinks the variable might somehow be
referenced in the initialization code at run time? It doesn't really make
sense to me.
 
P

proxyuser

Peter Duniho said:
For better or worse, the C# spec has very little to say on warnings
generally, and nothing at all with respect to those involving unused
variables. So, as far as the language definition goes, this is purely
optional behavior for the compiler. Hopefully it's not something you were
hoping to rely on.

Well, not really. It came up during code review. Some extraneous code got
checked in, and the developer thought the compiler would have caught that
mistake (we have warnings set to errors, so he thought the compile would
have failed if he left that sort of line around by mistake after testing his
code.) Thanks for the info though!
 
P

proxyuser

Peter Duniho said:
I'm not sure I agree 100%, but then that may be why I've never been
invited to help write a compiler. :)

I don't think I agree either, but it's nice to know someone at least gave
this some thought....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top