Use method to update member fields - CSharp Custom Type

CSharp examples for Custom Type:Field

Description

Use method to update member fields

Demo Code

using System;/*  w ww .  j a va  2s  . c  o m*/
class Robot
{
   private int currentFloorNumber;
   private int floorsTraveled;
   public Robot()
   {
      currentFloorNumber = 0;
      floorsTraveled = 0;
   }
   public void MoveToFloor(int toFloorNumber)
   {
      floorsTraveled += Math.Abs(currentFloorNumber - toFloorNumber);
      currentFloorNumber = toFloorNumber;
   }
   public int GetFloorsTraveled()
   {
      return floorsTraveled;
   }
   public int GetCurrentFloorNumber()
   {
      return currentFloorNumber;
   }
}
class RobotArray
{
   public static void Main()
   {
      Robot [] elevators = new Robot[10];
      for (int i = 0; i < elevators.Length; i++)
      {
         elevators[i] = new Robot();
      }
      elevators[0].MoveToFloor(10);
      elevators[4].MoveToFloor(20);
      elevators[0].MoveToFloor(5);
      elevators[4].MoveToFloor(7);

      for (int i = 0; i < elevators.Length; i++)
      {
         Console.WriteLine("Robot {0,2}:       {1,4}               {2,4}", (i + 1), elevators[i].GetFloorsTraveled(), elevators[i].GetCurrentFloorNumber());
      }
   }
}

Result


Related Tutorials