Definite Assignment
Definite assignment is a rule simply stating that every variable must have a value before it's read from. The process of assigning a value to a variable for the first time is known as initialization. Once the initialization process has taken place, a variable is considered initialized. If the initialization process has not yet taken place, a variable is considered to be uninitialized. Initialization ensures that variables have valid values when expressions are evaluated. Uninitialized variables are unassigned variables. If a program attempts to read from an unassigned variable, the compiler will generate an error.
For C++ Programmers
C++ programs are allowed to read data from uninitialized variables. C# will detect uninitialized variables at compile time and return an error.
Default initialization rules depend upon where a variable is declared in a program. For the purposes of default initialization, there are two types of variableslocal variables and class variables. Variables are initialized based upon whether they're class variables or local variables.
Local variables are uninitialized. Local variables are those variables declared within a method or other language element defined by a block. Blocks are language elements that denote the beginning and end of a C# language construct. In the case of methods, blocks denote the beginning and end of a method. Methods are C# language constructs allowing programmers to organize their code into groups. If a variable is declared within a method, it is considered to be a local variable.
This is different from class variables, which are declared as class members. Class members can be nearly any C# type or language element. Variables and methods are class members. Class variables are initialized to default values if a program's code does not explicitly initialize them. Table 6 lists each type's default values.
Table 6 Default Values of C# Types
Type |
Default Value |
bool |
False |
char |
\u0000 |
sbyte |
0 |
byte |
0 |
short |
0 |
ushort |
0 |
int |
0 |
uint |
0 |
long |
0 |
ulong |
0 |
float |
0.0f |
double |
0.0d |
decimal |
0.0m |