I have always been wondering about why in the following example it is OK to not initialize the instance field (relying that it will have its default value) and accessing it, while local variables apparently must be initialized, even if I initialize it to default value it would get anyway...
public class TestClass
{
private bool a;
public void Do()
{
bool b; // That would solve the problem: = false;
Console.WriteLine(a);
Console.WriteLine(b); //Use of unassigned local variable 'b'
}
}
For local variables, the compiler has a good idea of the flow - it can see a "read" of the variable and a "write" of the variable, and prove (in most cases) that the first write will happen before the first read.
This isn't the case with instance variables. Consider a simple property - how do you know if someone will set it before they get it? That makes it basically infeasible to enforce sensible rules - so either you'd have to ensure that all fields were set in the constructor, or allow them to have default values. The C# team chose the latter strategy.
It is governed by Definite Assignment rules in C#. Variable must be definitely assigned before it is accessed.
5.3 Definite assignment
At a given location in the executable code of a function member, a variable is said to be definitely assigned if the compiler can prove, by a particular static flow analysis (§5.3.3), that the variable has been automatically initialized or has been the target of at least one assignment.
5.3.1 Initially assigned variables
The following categories of variables are classified as initially assigned:
Static variables.
Instance variables of class instances.
Instance variables of initially assigned struct variables.
Array elements.
Value parameters.
Reference parameters.
Variables declared in a catch clause or a foreach statement.
5.3.2 Initially unassigned variables
The following categories of variables are classified as initially unassigned:
Instance variables of initially unassigned struct variables.
Output parameters, including the this variable of struct instance constructors.
Local variables, except those declared in a catch clause or a foreach statement.
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