Why can this var be declared and initialized in only one statement?

Why can this var be declared and initialized in only one statement in C #?

I mean, why can't we use:

var x; x = 100; 

Since this is the implicit typed local variable "var", and the compiler accepts a type that is correct for the variable assignment operator, why does it matter that it must be declared and initialized in only one expression?

+5
source share
5 answers

Because a statement declaring a variable must imply a type so that the compiler knows what to do with var . Of course, you, as a person with your own intuition, can logically go through the code and determine what type it will be. But the compiler is not as complex as human intuition. He needs the type defined in this statement to compile this statement as a logically completed action.

Each statement must individually be complete and compiled.

+12
source

Firstly, because the compiler is just that smart.

Secondly, because it actually reduces readability - you cannot quickly deduce the type of a variable by looking at its definition.

+3
source

This is not valid because you could do this:

 var a; if (someCondition) a = 3; else a = "abc"; 

C # needs to know the types of variables at compile time, in which case it will only know the type at run time.

+2
source

Basically, you ask why the compiler cannot determine the type at the first assignment, and not in the declaration, right? Consider the following:

 var x; if (DateTime.Now.Hour > 12) { x = 100; } else { x = "Hello"; } 

What should the compiler do? The if statement can only be evaluated at run time, and not at compile time, when the type needs to be identified. But at compile time, it can still be either an int or a string.

+2
source

var is really just syntactic sugar. This is abbreviated, so you do not need to write the type of the variable, but under the hoods C # is still a strongly typed language.

The compiler determines the type from the destination. Since you assign the next line, it cannot determine the type.

+1
source

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


All Articles