#36 – Variable Initialization and Definite Assignment
July 23, 2010 4 Comments
Variables must be assigned a value before they can be used. You can declare a variable without initializing it, but attempting to reference the value of the variable before you’ve given it a value will result in a compiler error.
int i; int j = i + 1; // Error: Use of unassigned local variable 'i'
This requirement of definite assignment before use means that you are never able to reference an unassigned variable in C#.
It’s considered good practice to initialize a variable when you declare it. This applies to both built-in types and custom types.
When you initialize a variable, the object that it references is said to be instantiated.
Person p = new Person(); int i = 0;
Pingback: #341 – Defining and Using Local Variables « 2,000 Things You Should Know About C#
If the initialization when declaring a variable is only to avoid the compile time error, I think it’s better not initialize it to avoid logic bugs.
I know it’s a good practice well accepted, and I also followed it for a long time. But as I review this practice, I cannot find a strong reason to avoid the compile time error but at the risk of introducing logic bugs.
I’m talking about:
“It’s considered good practice to initialize a variable when you declare it. “
The default value of the variable ‘i’ (all integers have a default value of 0) here is 0. So why cant the compiler use that value to perform addition and return of value of variable ‘j’ to be 1?