Assigned value, never used, but no compiler message

The whole program in the web form of the .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 create an application, the compiler emphasizes x,

The variable x is assigned, but its value is never used.

For y, I do not emphasize. Why not? (VS 2008, .Net 3.5)

+4
source share
3 answers

I will answer your question in detail:

fooobar.com/questions/282626 / ...

In short: the compiler detects that a local record is being written, but not read while passing through stream analysis. It deliberately suppresses the warning if the value written to the local is inconsistent. String.Empty not a constant, this field is read-only, oddly enough. But an empty string literal is a constant. That's why you see a warning for one with a literal, but not for a field.

The compiler argues that you can assign the value of an expression to unread from local to make debugging easier. We donโ€™t want you to have to turn off โ€œerror warningsโ€ every time you enter an explanatory variable to help with debugging. The fact that in this case, obviously, you are not using the variable to check the output of String.Empty , is lost in the compiler; he does not know what the semantics of field references are.

+9
source

the compiler emphasizes x,

No, the compiler does not. Editor emphasizes. The compiler does not have an output channel capable of drawing a string.

For y, I do not emphasize. Why not?

Because it is used?

Do not get me wrong, but without the full code corresponding to the scope of the variable, it is simply impossible to say whether this is true or not.

The whole program:

Lee This is not the whole program;) This is not even a complete class. And you cannot have a variable in C # outside the class.

+5
source

If I understand the article that I read correctly, the compiler does not know what String.Empty is because this field is read-only. String.Empty is assigned at runtime. Therefore, I do not see a warning when creating the program.

Article

-2
source

Source: https://habr.com/ru/post/1394137/


All Articles