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?
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:
While in C# local variables are not initialised, and the compiler won’t let you use them until they are:
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.