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....
Comments
Anonymous
November 07, 2005
This can lead to bugs in code as the compiler does not warn on un-initialized instance variables....
This is where FxCop (and other static code analysis tools) come in. Too bad that the static analysis tool isn't included in VS2005 Professional...Anonymous
November 08, 2005
I thought the compiler does warn you:
Field 'MyClass.i' is never assigned to, and will always have its default value 0Anonymous
November 08, 2005
This takes us to an interesting question, why DOESN'T the compiler initialise variables for us? In Java it is done for you and I don't see any problems with that.Anonymous
November 08, 2005
The comment has been removedAnonymous
January 22, 2006
Manip,
Java behaves exactly like C# (or perhaps that should be the other way around) in this regard. It will initialize instance fields but not variables automatically.
BrianAnonymous
October 01, 2009
class members are initialized. No worries of uninitialization here. Look at the link: http://msdn.microsoft.com/en-us/library/aa645756(VS.71).aspxAnonymous
October 01, 2009
Hanu not sure I understand your comment, what you said is the meaning of the post..