var
variables still have a type - and the compiler error message says this type must be established during the declaration.
The specific request (assigning an initial null value) can be done, but I don't recommend it. It doesn't provide an advantage here (as the type must still be specified) and it could be viewed as making the code less readable:
var x = (String)null;
Which is still "type inferred" and equivalent to:
String x = null;
The compiler will not accept var x = null
because it doesn't associate the null with any type - not even Object. Using the above approach, var x = (Object)null
would "work" although it is of questionable usefulness.
Generally, when I can't use var
's type inference correctly then
The second approach can be done by moving code into methods or functions.