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

{

public int 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 (7)
  1. Anders Dalvander says:

    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…

  2. Ron Krauter says:

    I thought the compiler does warn you:

    Field ‘MyClass.i’ is never assigned to, and will always have its default value 0

  3. Manip says:

    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.

  4. Ron, the compiler warns based on the warning level you set. So if the above code is in program.cs and you run

    csc Program.cs /warn:4 you’ll get the warning.

    For all other levels (0-3) this warning is not given.

    This is OK for command line builds because the default level is 4. However if you are building thru the IDE then a different default warning level is used (I don’t remember which one) and this warning does not come…..

  5. Brian Duff says:

    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.

    Brian

  6. Hanu says:

    class members are initialized. No worries of uninitialization here. Look at the link:

    http://msdn.microsoft.com/en-us/library/aa645756(VS.71).aspx

  7. Hanu not sure I understand your comment, what you said is the meaning of the post..

Comments are closed.

Skip to main content