I am getting eror like use of unassigned variable totalhourrate.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aarathy
    New Member
    • Mar 2019
    • 1

    I am getting eror like use of unassigned variable totalhourrate.

    Code:
    using static System.Console;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace MoveEstimator
    {
        class MoveEstimator
        {
            static void Main(string[] args)
            {
                const  int baserate=200;
                const int rateperhour = 150;
                const int ratepermile = 20;
                
                int totalhourrate, totalmiles;
                for (int numhours=1, nummiles = 1;  numhours <= 24 && nummiles <= 100; numhours++,nummiles++)
                {
                    WriteLine("Enter the number of hours worked", numhours);
                    ReadKey();
                    totalhourrate = numhours * rateperhour;
                    WriteLine("\nTotal rate of hours worked: " + totalhourrate);
                   
    
               
                    WriteLine("\n Enter the number of miles", nummiles);
                    ReadKey();
                    totalmiles = nummiles * ratepermile;
                    WriteLine("\n Total miles covered: " +totalmiles);
                    
                      
    
                }
                ReadLine();
                int totalfee = baserate + totalhourrate + totalmiles;
                WriteLine("\n The total fee is: " +totalfee);
                ReadKey();
    
    
            }
        }
    }
    Last edited by gits; Mar 22 '19, 12:16 PM. Reason: added code tags
  • Luuk
    Recognized Expert Top Contributor
    • Mar 2012
    • 1043

    #2
    You should move line #17 ("int totalhourrate, totalmiles;")
    to just before line #11 ("static void Main(string[] args)")
    and add 'private static ' in front of it.

    Or you could initialize those vars at line #17, changing that line to:
    Code:
    int totalhourrate = 0, totalmiles = 0;
    The explanation about this is here: CS0165
    The C# compiler does not allow the use of uninitialized variables. If the compiler detects the use of a variable that might not have been initialized, it generates compiler error CS0165. ...

    Comment

    • Ishan Shah
      New Member
      • Jan 2020
      • 47

      #3
      Local variables aren't initialized. so, You have to manually initialize them because members are initialized but locals are not. That's why you get the compiler error.

      Code:
      int totalhourrate, totalmiles; //This is not initialized and must be assigned before used.
      So your code must be like the following :

      Code:
      int totalhourrate=0;
      int totalmiles=0;

      Comment

      Working...