I want to assign a variable to an initial value of null, and assign its value in the next if
-else
block, but the compiler is giving an error,
Implicitly-typed local variables must be initialized.
How could I achieve this?
value − Any value to initialize the variable. By default, it is zero.
The way of initializing a variable is very similar to the use of PARAMETER attribute. More precisely, do the following to initial a variable with the value of an expression: add an equal sign (=) to the right of a variable name. to the right of the equal sign, write an expression.
If the variable is in the scope of of a function and not a member of a class I always initialize it because otherwise you will get warnings. Even if this variable will be used later I prefer to assign it on declaration. As for member variables, you should initialize them in the constructor of your class.
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.
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