Initialize value of 'var' in C# to null

c#, var

Solution

`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

- I am at a place where it's best to declare the variable explicitly; or

- I should rewrite the code such that a valid value (with an established type) is assigned during the declaration.

The second approach can be done by moving code into methods or functions.

Problem

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?

Original source

Related problems