Why is that var can only be declared and initialized in a single statement in C#?
I mean why we cannot use:
var x;
x = 100;
Since it is a implicit typed local variable "var" and the compiler takes the type that is right of the variable assignment operator, why would it matter that it should be only declared and initialized in a single statement?
You can initialize as many as you want of any type, but should you use an inline declaration, all declared variables must be of the same type, as pst sort of mentioned.
In C#, the compiler does not allow you to assign a null value to a variable.
Because the statement which declares the variable needs to imply the type in order for the compiler to know what to do with var
. Sure, you as a person with your own intuition can logically step through the code and determine what the type will be. But the compiler isn't as complex as human intuition. It needs the type defined in that statement in order to compile that statement as a logically complete action.
Every statement needs to individually be complete and compilable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With