Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is that var can only be declared and initialized in a single statement?

Tags:

c#

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?

like image 803
Joe Avatar asked Sep 30 '15 13:09

Joe


People also ask

How many variables can be initialized at a time?

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.

Can we assign null value to var in C#?

In C#, the compiler does not allow you to assign a null value to a variable.


1 Answers

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.

like image 199
David Avatar answered Oct 14 '22 09:10

David