Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of instance fields vs. local variables

Tags:

c#

.net

clr

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'
    }
  }
like image 301
flq Avatar asked Oct 09 '09 09:10

flq


2 Answers

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.

like image 59
Jon Skeet Avatar answered Oct 23 '22 12:10

Jon Skeet


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.

like image 26
Dzmitry Huba Avatar answered Oct 23 '22 13:10

Dzmitry Huba