Link to home
Start Free TrialLog in
Avatar of brillox
brilloxFlag for United Kingdom of Great Britain and Northern Ireland

asked on

static use doubt

I do not understand why in the code below I can have the statement
 
*** private Person passenger;     without using the static keyword

and in the statement

*** private  static Elevator elevatorA;  if I delete the static keyword I get a compiler error

I am a bit confused with the use of static .....






using System;

class Elevator
{
      private int currentFloor = 1;
      private int requestedFloor = 0;
      private int totalFloorsTravelled = 0;
      private Person passenger;
      
      public void LoadPassenger()
      {
            passenger = new Person();                        
      }
      
      public void InitiateNewFloorRequest()
      {
            requestedFloor = passenger.NewFloorRequest();
            Console.WriteLine("Departing floor: " + currentFloor + " Travelling to floor: " +  requestedFloor);
            totalFloorsTravelled = totalFloorsTravelled + Math.Abs(currentFloor - requestedFloor);
            currentFloor = requestedFloor;
      }
      
      public void ReportStatistic()
      {      
            Console.WriteLine("Total floors travelled: " + totalFloorsTravelled);
      }
}

class Person
{
      private System.Random randomNumberGenerator;
      
      public Person()
      {
            randomNumberGenerator = new System.Random();
      }
      
      public int NewFloorRequest()
      {
            return randomNumberGenerator.Next(1,30);
      }
}

class Building
{
      private  static Elevator elevatorA;
      
      public static void Main()
      {
            elevatorA = new Elevator();
            
            for(int i = 0; i == 5; i ++)
            {
                  elevatorA.InitiateNewFloorRequest();
            }
      }
}
ASKER CERTIFIED SOLUTION
Avatar of WinterMuteUK
WinterMuteUK
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Infact to change building easier:

  class Building
  {
    private Elevator elevatorA;

    public static void Main(){
      Building building = new Building();
      building.elevatorA = new Elevator();

      for(int i = 0; i == 5; i++)
          building.elevatorA.InitiateNewFloorRequest();
    }

You don't need the property to access the member variable, nor the default constructor...! D'oh!

Wint
Helloo,
             we can use only the static Methods/Members with in the Main method. try the following example.

     class tmp
     {
          // it will raise an error because the variable should be static
          // static int x = 10;
                int x=10;

           public static void Main()
           {
                 Console.WriteLine(x);
            }
     }