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?
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.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With