C# allows you to use var
to specify that the type will be evaluated some other way than explicitly stating it. That's quite handy for code that used to look like this:
Type<string,int,int,int,int> xyzzy = new Type<string,int,int,int,int>();
Now you can instead do:
var xyzzy = new Type<string,int,int,int,int>();
However, the variable itself is still statically typed, so the type must be available at the point where the variable is created, so that the compiler can know what to do with it.
The clue lies in the error message you see:
Implicitly-typed local variables must be initialized
Note that it's implicitly-typed rather than untyped.
So, of these:
int x; // explicit int.
var x = 7; // implicit int because we're using int to set it.
var x; // no idea what type this should be.
the first two are okay because the type information is available. The third is not okay because the information as to what type you want is not available.
Contrast the use of var
with dynamic
- the latter is more closely related to var
in Javascript, it's dynamically typed(a) and figuring out what can be done to it is deferred until run-time.
(a) Technically, I think it's still considered a static type but the regular type checking is bypassed at compile time.