About unassigned variables
c#
Solution
Because other variables are initialized with their default value.
Jon Skeet has already found some interesting words on this issue:
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.
and here's the related C# language specification:
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.
Problem
Just curious, I'm not trying to solve any problem. Why only local variables should be assigned? In the following example: ``` class Program { static int a; static int b { get; set; } static void Main(string[] args) { int c; System.Console.WriteLine(a); System.Console.WriteLine(b); System.Console.WriteLine(c); } } ``` Why `a` and `b` gives me just a warning and `c` gives me an error? Addionally, why I can't just use the default value of Value Type and write the following code? ``` bool MyCondition = true; int c; if (MyCondition) c = 10; ``` Does it have anything to do with memory management?