Why C# local variables must be initialized?

Local variables have to be assigned before they can be used. Class fields however get their default value.

An example:

public bool MyMethod()
{
    bool a;

    Console.Write(a); // This is NOT OK.

    bool b = false;

    Console.Write(b); // This is OK.
}

class MyClass
{
    private bool _a;

    public void MyMethod()
    {
        Console.Write(_a); // This is OK.
    }
}

The book is mostly correct when it comes to VB, but it fails to mention the difference between VB and C# in this case.

In VB all local variables are automatically initialised:

Sub Test()
  Dim x As Integer
  MessageBox.Show(x.ToString()) 'shows "0"
End Sub

While in C# local variables are not initialised, and the compiler won't let you use them until they are:

void Test() {
  int x;
  MessageBox.Show(x.ToString()); // gives a compiler error
}

Also, it's not clear whether the quote from the book is actually talking about local variables or class member variables. Class member variables are always initialised when the class instance is created, both in VB and C#.

The book is wrong when it says that "Value types have an implicit constructor". That is simply not true. A value type is initialised to its default value (if it's initialised), and there is no call to a constructor when that happens.


You need to assign something to b first otherwise it doesn't get initialized.

try:

bool b = false; 
Console.WriteLine("The value of b is " + b); 

b is now false.