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)
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.Emptyis 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.Emptyis lost upon the compiler; it does not know what the semantics of the field reference are.