Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize value of 'var' in C# to null [duplicate]

Tags:

c#

var

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?

like image 837
Nikhil Chavan Avatar asked Jul 02 '13 04:07

Nikhil Chavan


People also ask

What is the initial value of a variable in C?

value − Any value to initialize the variable. By default, it is zero.

How do you initialize a variable?

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.

Why do we initialize variables in C?

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.


1 Answers

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

  1. I am at a place where it's best to declare the variable explicitly; or
  2. 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.

like image 191
user2246674 Avatar answered Sep 21 '22 17:09

user2246674