VisualStudio2008 is weird from compiler warning, explanation needed

Just a quick question for the VisualStudio 2008 compiler.

We really included that warning compilers are seen as errors that work fine, but today I found out that the following behavior:

static void Main(string[] args) { int number = 0; DateTime dateTime = DateTime.Now; } 

Compiling this fragment leads to only one warning: "The variable" number "is assigned, but its value is never used."

Can someone explain the difference to me why a variable causes an error, but not a dateTime variable?

Well, it looks like this has something to do with literals. Given the following code:

 static void Main(string[] args) { string str1 = "Foo"; string str2 = str1; } 

Compiling with both lines does not result in a warning, although the variable str2 is never mentioned. If you comment on the string string str2 = str1; , a warning appears for the variable "str1" is never used.

+4
source share
4 answers

Eric Lippert wrote an article about this, so I will leave it to him to explain:

Usually C # warns about all variables and fields that are never read, never, etc. But in this case, we suppress the warning on purpose if the assignment is not an expression constant.

This is because there is no good way in the Visual Studio debugger to say "show me the return value of the last function call." Although I agree, you should reasonably indicate that the way to solve this is to fix the debugger, given that I do not have the ability. To fix this, we need a solution in C # for our clients.

See the article for further explanation.

+2
source

This is because DateTime.Now is a property, not a literal. Property getters can have side effects, just calling can be useful on its own. Not that it is a good idea, but it is not, and it is not, and the compiler is not smart enough to say whether it really does. In any case, it cannot, ultimately, calls the operating system code to obtain the current system time.

+5
source

I assume the operator is int number = 0; completely free from side effects and can be identified as unnecessary by the compiler. DateTime dateTime = DateTime.Now; , on the other hand, is an estimate of a static property and can potentially execute other code, so the compiler does not identify it as an unused variable. In other words, although a variable may not be used, the action of its assignment could potentially do something else.

+3
source

DateTime.Now is a link. I could be wrong, since I have no experience with C #, but I don’t think you are creating a new object using DateTime.Now.

-3
source

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


All Articles