Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

value assigned, never used, but no compiler message

Tags:

variables

c#

The whole program in a web form of a .net web-application:

namespace WebApplication1
{
   public partial class WebForm1 : System.Web.UI.Page
   {
     protected void Page_Load(object sender, EventArgs e)
     {
        string x = "";
        string y = String.Empty;
     }
   }
}

If I build the application, the compiler underlines x,

The variable x is assigned to but it´s value is never used

For y, I get no underlining. Why not? (VS 2008, .Net 3.5)

like image 487
AGuyCalledGerald Avatar asked Dec 17 '22 04:12

AGuyCalledGerald


2 Answers

I answer your question in detail here:

https://stackoverflow.com/a/2741281/88656

Briefly: the compiler detects that the local is written to but not read during the flow analysis pass. It deliberately suppresses the warning if the value written to the local is a non-constant. String.Empty is not a constant, it is a read-only field, oddly enough. But the empty string literal is a constant. That is why you see the warning for the one with the literal but not for the field.

The compiler is reasoning that you might be assigning the value of the expression to an unread-from local in order to facilitate debugging the program. We do not want you to have to turn "warnings are errors" off every time you introduce an explanatory variable to assist in debugging. The fact that in this case, obviously you are not using the variable to examine the output of String.Empty is lost upon the compiler; it does not know what the semantics of the field reference are.

like image 76
Eric Lippert Avatar answered Jan 05 '23 16:01

Eric Lippert


the compiler underlines x,

No, the compiler does not. The editor underlines. The compiler has no output channel capable of drawing a line.

For y, I get no underlining. Why not?

Because it is used?

Do not get me wrong, but without the complete code relevant by variable scope there simply is no way to say whether this is like that or not.

The whole program:

Lie. This is not the whole program ;) It is not even the complete class. And you can not have a variable in C# outside of a class.

like image 22
TomTom Avatar answered Jan 05 '23 16:01

TomTom