C#: Uninitialized instance variables
int i;Console.WriteLine(i);
The above code will fail to compile. This is because the C# compiler requires a variable to be definitely assigned at the location where it is used. It figures this out using static flow analysis and the above case is the easiest catch for it.
However, there is a small trivia regarding this. Lets consider the following code
class MyClass{ publicint i; public MyClass() { }}class Program{ static void Main(string[] args) { MyClass myclass = new MyClass(); Console.WriteLine(myclass.i); }}
This piece of code will compile and run and the output will be 0. A first look reveals that i has not been initialized as i is not static and we have not initialized it in the constructor of MyClass, but still it is initialized to 0. The reason can be found in the Section 5.3.1 of C# spec. It lists the types of variables that are intially assigned. The list goes as
• 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.
Since instance variables of class instances are initialized the code builds and runs. This can lead to bugs in code as the compiler does not warn on un-initialized instance variables....