Section 5.3. Definite Assignment

   

5.3 Definite Assignment

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 5-1 to:

 int myInt; 

and save the revised program shown in Example 5-2.

Example 5-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 5-2, the C# compiler will display the following error message:

 5.2.cs(6,55): error CS0165: 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 5-3 illustrates a corrected program.

Example 5-3. Definite assignment
 class Values {    static void Main( )    {       int myInt;       //other code here...       myInt = 7;  // assign to it       System.Console.WriteLine("Assigned, myInt: {0}", myInt);       myInt = 5;       System.Console.WriteLine("Reassigned, myInt: {0}", myInt);    } } 
   


Learning C#
Learning C# 3.0
ISBN: 0596521065
EAN: 2147483647
Year: 2005
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net