C# requires definite assignment ; that is, variables must be initialized (or assigned to) before they are
“used.” To test this rule, change the line that initializes myInt
in Example 3-1 to:
int myInt;
Save the revised program shown in Example 3-2.
Example 3-2. Uninitialized variable
class Values { static void Main( ) { int myInt; System.Console.WriteLine ("Uninitialized, myInt: {0}",myInt); myInt = 5; System.Console.WriteLine("Assigned, myInt: {0}", myInt); } }
When you try to compile Example 3-2, the C# compiler will display the following error message:
Use of unassigned local variable 'myInt'
It is not legal to use an uninitialized variable in C#; doing so
violates the rule of definite assignment. In this case, “using” the
variable myInt
means passing it to
WriteLine( )
.
So does this mean you must initialize every variable? No, but if you don’t initialize your variable, then you must assign a value to it before you attempt to use it. Example 3-3 illustrates a corrected program.