Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C# local variables must be initialized?

I am reading MCTS Self Paced Training Kit (70-536) Edition 2 and in the 1st chapter we have the following.

How to Declare a Value Type Variable To use a type, you must first declare a symbol as an instance of that type. Value types have an implicit constructor, so declaring them instantiates the type automatically; you don’t have to include the New keyword as you do with classes. The constructor assigns a default value (usually null or 0) to the new instance, but you should always explicitly initialize the variable within the declaration, as shown in the following code block:

'VB

Dim b As Boolean = False    

// C#  
bool b = false;

However, when I compile the following Console Application,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ch1_70_536
{
    class Program
    {
        static void Main(string[] args)
        {
            bool b;
            Console.WriteLine("The value of b is " + b);
            Console.ReadKey();
        }
    }
}

I get the Compile Time Error

"Use of Unassigned Local Variable b"

It is not even mentioned in the Errata. Am I doing something wrong or is the book completely wrong?

like image 643
Kanini Avatar asked Nov 15 '10 08:11

Kanini


1 Answers

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.
    }
}
like image 65
Pieter van Ginkel Avatar answered Jan 04 '23 12:01

Pieter van Ginkel