Section 3.4. Definite Assignment


3.4. 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 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.

Example 3-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# 2005
Learning C# 2005: Get Started with C# 2.0 and .NET Programming (2nd Edition)
ISBN: 0596102097
EAN: 2147483647
Year: 2004
Pages: 250

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