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
You need to assign a value to b
bool b = false;
Until you assign it a value it is "unassigned"
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.
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.
}
}
In C# local variables are stored in the stack and the compiler does not initialize them to have code optimization.
So the reference, that is in fact a pointer even for value types, points to a undefinded memory space.
Thus if we use a local variable without setting it to someting before, the compiler know that we will get random data.
Here a sample IL code:
static void Test()
{
int a;
int b = 2;
}
.method private hidebysig static
void Test () cil managed
{
// Method begins at RVA 0x3044
// Code size 4 (0x4)
.maxstack 1
.locals init (
[0] int32 a,
[1] int32 b
)
// (no C# code)
IL_0000: nop
// int num = 2;
IL_0001: ldc.i4.2
IL_0002: stloc.1
// }
IL_0003: ret
} // end of method Program::Test
Int32
is defined in the stack at position 0
for a
but it is not assigned to a default value.
So its value is undetermined and can have any value from the memory cells.
For b
at position 1
, it is assigned later and all is fine.
This statement really should be elaborated to indicate that, although a local variable can be declared without assigning it a value, it cannot be used until it has been assigned an initial value:
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...
A variable in a method (method scope) needs to be initialized explicitly. A variable (or 'field') at class level is initialized automatically with the default value.
class Test
{
bool b; // =false
int i; // =0
}