Constants

Introduction

A constant is a value that never changes. Examples are 244, "ASEC Mimosa", or 39.37. These are constant values you can use in your program any time. You can also declare a variable and make it a constant; that is, use it so that its value is always the same.

Practical LearningPractical Learning: Introducing Constants

  1. Start Microsoft Visual Studio
  2. Create a new Console App named MetropolitanTransitSystem1

Creating a Constant

To let you create a constant, the C# language provides a keyword named const. To create a constant, you start by declaring a variable. Before the data type of the variable, type the const keyword. You must initialize that variable with an appropriate value based on the data type of the variable. Here is an example:

const double ConversionFactor = 39.37;

Once a constant has been created and it has been appropriately initialized, you can use its name where the desired constant would be used. Here is an example of a constant variable used many times:

using static System.Console;

const double conversionFactor = 39.37;
double meter, inch;

meter = 12.52;
inch = meter * conversionFactor;

Write(meter);
Write(" = ");
Write(inch);
WriteLine("in\n");

meter = 12.52;
inch = meter * conversionFactor;

Write(meter);
Write(" = ");
Write(inch);
WriteLine("in\n");

meter = 12.52;
inch = meter * conversionFactor;

Write(meter);
Write(" = ");
Write(inch);
WriteLine("in\n");

This would produce:

12.52 = 492.9124in

12.52 = 492.9124in

12.52 = 492.9124in

Press any key to close this window . . .

To initialize a constant variable, the value on the right side of "=" must be a constant or a value that the compiler can determine as constant. Instead of using a known constant, you can also assign it another variable that has already been declared as constant.

A Constant Boolean Variable

If you are planning to use a Boolean variable whose value will never change, you can declare it as a constant. To do this, apply the const keyword to the variable and initialize it. Here is an example:

const bool driverIsSober = true;

Constant Fields in a Type

When creating a field in a class, a record, or a structure, if you know that the value of that field will never change, create that field as a constant. That is, precede the data type of the field with the const keyword. Of course, you must initialize the field. Here is an example:

public record CustomerOrder
{
    const double originalPrice = 124.50;

    int discountRate = 20;
    double discountAmount = 0;
}

If the field will be accessed outside the class, you should mark it with the public or the internal keyword. If the field will be accessed only inside the class, you can omit any access keyword or mark it as private. After creating the field, you can use it and make sure you don't change its value.

Practical LearningPractical Learning: Creating and Using Constants

  1. Change the document as follows:
    using static System.Console;
    
    CustomerOrder custOrder = new CustomerOrder();
    
    custOrder.PresentCustomerOrder();
    
    public record CustomerOrder
    {
        const double originalPrice = 124.50;
    
        int discountRate      = 20;
        double discountAmount = 0;
        double markedPrice    = 0;
        double number_of_days_in_store = 75;
    
        void EvaluateDiscount()
        {
            if (number_of_days_in_store is <= 45)
                discountRate = 25;
        }
    
        void ProcessOrder()
        {
            discountAmount = originalPrice * discountRate / 100.00;
    
            markedPrice = originalPrice - discountAmount;
        }
    
        public void PresentCustomerOrder()
        {
            EvaluateDiscount();
            ProcessOrder();
    
            WriteLine("Fun Department Store");
            WriteLine("----------------------------------");
            WriteLine($"Original Price:  {originalPrice}");
            WriteLine($"Days in Store:   {number_of_days_in_store}");
            WriteLine($"Discount Rate:   {discountRate:n}");
            WriteLine($"Discount Amount: {discountAmount:n}");
            WriteLine($"Marked Price:    {markedPrice:n}");
            WriteLine("==================================");
        }
    }
  2. To test the application, on the main menu, click Debug and click Start Without Debugging:
    Fun Department Store
    ----------------------------------
    Original Price:  124.5
    Days in Store:   75
    Discount Rate:   20.00
    Discount Amount: 24.90
    Marked Price:    99.60
    ==================================
    
    Press any key to close this window . . .
  3. Press Q to close the window and return to your programming environ
  4. To create a folder, in the Solution Explorer, right-click the name of the project -> Add -> Folder
  5. Type Models as the name of the folder and press Enter
  6. To create a class, in the Solution Explorer, right-click Models -> Add -> Class
  7. Type MetroStation as the name of the class
  8. Click Add
  9. Change the document as follows:
    namespace MetropolitanTransitSystem1.Models
    {
        public record MetroStation
        {
            public int      StationId                     { get; set; }
            public short    StationNumber                 { get; set; }
            public string?  StationName                   { get; set; }
            public (string? City, string? State) Location { get; set; }
            public bool     ParkingAvailable              { get; set; }
            public int      BikeRacks                     { get; set; }
        }
    }
    
  10. To create another class, in the Solution Explorer, right-click Models -> Add -> Class
  11. Type MetroLine as the name of the class
  12. Click Add
  13. Change the document as follows:
    namespace MetropolitanTransitSystem1.Models
    {
        public record MetroLine(int LineId, string? LineName, short Between, short And);
    }
  14. To create another class, in the Solution Explorer, right-click Models -> Add -> Class
  15. Type StationAndLine as the name of the class
  16. Click Add
  17. Change the document as follows:
    namespace MetropolitanTransitSystem1.Models
    {
        public record StationAndLine(int LinedStationId, short StationNumber, string? LineName);
    }
  18. To create another class, in the Solution Explorer, right-click Models -> Add -> Class
  19. Type Database as the name of the class
  20. Click Add
  21. Change the document as follows:
    namespace MetropolitanTransitSystem10.Models
    {
        internal class Database
        {
            public MetroLine[]      Lines            { get; set; } = new MetroLine[6];
            public MetroStation[]   Stations         { get; set; } = new MetroStation[98];
            public StationAndLine[] StationsAndLines { get; set; } = new StationAndLine[154];
    
            public Database()
            {
                Stations[0]  = new MetroStation() { StationId =  1, StationNumber = 9374, StationName = "Congress Heights", Location = ("SE, Washington", "DC"), ParkingAvailable = false, BikeRacks = 10 };
                Stations[1]  = new MetroStation() { StationId =  2, StationNumber = 2859, StationName = "Franconia-Springfield", Location = ("Springfield", "VA"), ParkingAvailable = true, BikeRacks = 30 };
                Stations[2]  = new MetroStation() { StationId =  3, StationNumber = 6083, StationName = "New Carrollton", Location = ("New Carrollton", "MD"), ParkingAvailable = true, BikeRacks = 35 };
                Stations[3]  = new MetroStation() { StationId =  4, StationNumber = 4480, StationName = "Metro Center", Location = ("NW, Washington ", "DC"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[4]  = new MetroStation() { StationId =  5, StationNumber = 1584, StationName = "East Falls Church", Location = ("Arlington", "VA"), ParkingAvailable = true, BikeRacks = 87 };
                Stations[5]  = new MetroStation() { StationId =  6, StationNumber = 6295, StationName = "Wheaton", Location = ("Wheaton", "MD"), ParkingAvailable = true, BikeRacks = 26 };
                Stations[6]  = new MetroStation() { StationId =  7, StationNumber = 3815, StationName = "Minnesota Ave", Location = ("NE, Washington ", "DC"), ParkingAvailable = true, BikeRacks = 14 };
                Stations[7]  = new MetroStation() { StationId =  8, StationNumber = 8684, StationName = "Crystal City", Location = ("Arlington", "VA"), ParkingAvailable = false, BikeRacks = 10 };
                Stations[8]  = new MetroStation() { StationId =  9, StationNumber = 5248, StationName = "NoMa-Gallaudet U", Location = ("NE, Washington", "DC"), ParkingAvailable = false, BikeRacks = 10 };
                Stations[9]  = new MetroStation() { StationId = 10, StationNumber = 9393, StationName = "Ashburn", Location = ("Ashburn", "VA"), ParkingAvailable = true, BikeRacks = 51 };
                Stations[10] = new MetroStation() { StationId = 11, StationNumber = 6497, StationName = "Twinbrook", Location = ("Rockville", "MD"), ParkingAvailable = true, BikeRacks = 45 };
                Stations[11] = new MetroStation() { StationId = 12, StationNumber = 2969, StationName = "Woodley Park-Zoo/Adams Morgan", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 30 };
                Stations[12] = new MetroStation() { StationId = 13, StationNumber = 8686, StationName = "Eisenhower Avenue", Location = ("Arlington", "VA"), ParkingAvailable = false, BikeRacks = 14 };
                Stations[13] = new MetroStation() { StationId = 14, StationNumber = 4836, StationName = "Georgia Ave-Petworth", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 21 };
                Stations[14] = new MetroStation() { StationId = 15, StationNumber = 2841, StationName = "Rosslyn", Location = ("Arlington", "VA"), ParkingAvailable = false, BikeRacks = 14 };
                Stations[15] = new MetroStation() { StationId = 16, StationNumber = 2082, StationName = "Benning Road", Location = ("NE, Washington", "DC"), ParkingAvailable = false, BikeRacks = 4 };
                Stations[16] = new MetroStation() { StationId = 17, StationNumber = 8486, StationName = "Arlington Cemetery", Location = ("Arlington", "VA"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[17] = new MetroStation() { StationId = 18, StationNumber = 5575, StationName = "Dupont Circle", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 26 };
                Stations[18] = new MetroStation() { StationId = 19, StationNumber = 9638, StationName = "Reston Town Center", Location = ("Reston", "VA"), ParkingAvailable = false, BikeRacks = 40 };
                Stations[19] = new MetroStation() { StationId = 20, StationNumber = 3584, StationName = "Gallery Place Chinatown", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[20] = new MetroStation() { StationId = 21, StationNumber = 7597, StationName = "West Hyattsville", Location = ("Hyattsville", "MD"), ParkingAvailable = true, BikeRacks = 87 };
                Stations[21] = new MetroStation() { StationId = 22, StationNumber = 4975, StationName = "Shaw-Howard U", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[22] = new MetroStation() { StationId = 23, StationNumber = 2014, StationName = "Shady Grove", Location = ("Rockville", "MD"), ParkingAvailable = true, BikeRacks = 68 };
                Stations[23] = new MetroStation() { StationId = 24, StationNumber = 5395, StationName = "McPherson Square", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[24] = new MetroStation() { StationId = 25, StationNumber = 7497, StationName = "Clarendon", Location = ("Arlington", "VA"), ParkingAvailable = false, BikeRacks = 24 };
                Stations[25] = new MetroStation() { StationId = 26, StationNumber = 9794, StationName = "Fort Totten", Location = ("NE, Washington", "DC"), ParkingAvailable = true, BikeRacks = 22 };
                Stations[26] = new MetroStation() { StationId = 27, StationNumber = 3975, StationName = "Downtown Largo", Location = ("Largo", "MD"), ParkingAvailable = true, BikeRacks = 38 };
                Stations[27] = new MetroStation() { StationId = 28, StationNumber = 1575, StationName = "Braddock Road", Location = ("Alexandria", "VA"), ParkingAvailable = true, BikeRacks = 58 };
                Stations[28] = new MetroStation() { StationId = 29, StationNumber = 8473, StationName = "Naylor Road", Location = ("Hillcrest Heights", "MD"), ParkingAvailable = true, BikeRacks = 10 };
                Stations[29] = new MetroStation() { StationId = 30, StationNumber = 5297, StationName = "Innovation Center", Location = ("Herndon", "VA"), ParkingAvailable = true, BikeRacks = 177 };
                Stations[30] = new MetroStation() { StationId = 31, StationNumber = 7118, StationName = "Farragut West", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[31] = new MetroStation() { StationId = 32, StationNumber = 1155, StationName = "Suitland", Location = ("Suitland", "MD"), ParkingAvailable = true, BikeRacks = 7 };
                Stations[32] = new MetroStation() { StationId = 33, StationNumber = 3330, StationName = "Brookland-CUA", Location = ("NE, Washington", "DC"), ParkingAvailable = false, BikeRacks = 47 };
                Stations[33] = new MetroStation() { StationId = 34, StationNumber = 5739, StationName = "Grosvenor-Strathmore", Location = ("North Bethesda", "MD"), ParkingAvailable = true, BikeRacks = 24 };
                Stations[34] = new MetroStation() { StationId = 35, StationNumber = 1486, StationName = "Archives-Navy Memorial-Penn Quarter", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[35] = new MetroStation() { StationId = 36, StationNumber = 7946, StationName = "McLean", Location = ("McLean", "VA"), ParkingAvailable = false, BikeRacks = 36 };
                Stations[36] = new MetroStation() { StationId = 37, StationNumber = 2938, StationName = "Cheverly", Location = ("Cheverly", "MD"), ParkingAvailable = true, BikeRacks = 28 };
                Stations[37] = new MetroStation() { StationId = 38, StationNumber = 5947, StationName = "Judiciary Square", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[38] = new MetroStation() { StationId = 39, StationNumber = 8111, StationName = "Ballston-MU", Location = ("Arlington", "VA"), ParkingAvailable = false, BikeRacks = 22 };
                Stations[39] = new MetroStation() { StationId = 40, StationNumber = 1770, StationName = "Tenleytown-AU", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 20 };
                Stations[40] = new MetroStation() { StationId = 41, StationNumber = 3974, StationName = "Pentagon", Location = ("Arlington", "VA"), ParkingAvailable = false, BikeRacks = 6 };
                Stations[41] = new MetroStation() { StationId = 42, StationNumber = 6866, StationName = "Mt Vernon Sq 7th St-Convention Center", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 5 };
                Stations[42] = new MetroStation() { StationId = 43, StationNumber = 8374, StationName = "Capitol Heights", Location = ("Capitol Heights", "MD"), ParkingAvailable = true, BikeRacks = 25 };
                Stations[43] = new MetroStation() { StationId = 44, StationNumber = 2493, StationName = "Van Ness-UDC", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 18 };
                Stations[44] = new MetroStation() { StationId = 45, StationNumber = 5592, StationName = "King St-Old Town", Location = ("Alexandria", "VA"), ParkingAvailable = false, BikeRacks = 42 };
                Stations[45] = new MetroStation() { StationId = 46, StationNumber = 7720, StationName = "Union Station", Location = ("NE, Washington", "DC"), ParkingAvailable = false, BikeRacks = 8 };
                Stations[46] = new MetroStation() { StationId = 47, StationNumber = 1862, StationName = "Greenbelt", Location = ("Beltsville", "MD"), ParkingAvailable = true, BikeRacks = 81 };
                Stations[47] = new MetroStation() { StationId = 48, StationNumber = 4084, StationName = "Potomac Yard", Location = ("Alexandria", "VA"), ParkingAvailable = false, BikeRacks = 49 };
                Stations[48] = new MetroStation() { StationId = 49, StationNumber = 9795, StationName = "Medical Center", Location = ("Bethesda", "MD"), ParkingAvailable = false, BikeRacks = 48 };
                Stations[49] = new MetroStation() { StationId = 50, StationNumber = 2860, StationName = "Wiehle-Reston East", Location = ("Reston", "VA"), ParkingAvailable = true, BikeRacks = 15 };
                Stations[50] = new MetroStation() { StationId = 51, StationNumber = 9475, StationName = "Federal Center SW", Location = ("SW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[51] = new MetroStation() { StationId = 52, StationNumber = 8263, StationName = "Waterfront", Location = ("SW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[52] = new MetroStation() { StationId = 53, StationNumber = 9537, StationName = "College Park-U of Md", Location = ("College Park", "MD"), ParkingAvailable = true, BikeRacks = 81 };
                Stations[53] = new MetroStation() { StationId = 54, StationNumber = 3383, StationName = "Huntington", Location = ("Alexandria", "VA"), ParkingAvailable = true, BikeRacks = 32 };
                Stations[54] = new MetroStation() { StationId = 55, StationNumber = 7468, StationName = "Friendship Heights", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 28 };
                Stations[55] = new MetroStation() { StationId = 56, StationNumber = 1475, StationName = "Silver Spring", Location = ("Silver Spring", "MD"), ParkingAvailable = false, BikeRacks = 39 };
                Stations[56] = new MetroStation() { StationId = 57, StationNumber = 5022, StationName = "West Falls Church", Location = ("Falls Church", "VA"), ParkingAvailable = true, BikeRacks = 40 };
                Stations[57] = new MetroStation() { StationId = 58, StationNumber = 3947, StationName = "L'Enfant Plaza", Location = ("SW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 9 };
                Stations[58] = new MetroStation() { StationId = 59, StationNumber = 6470, StationName = "Pentagon City", Location = ("Arlington", "VA"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[59] = new MetroStation() { StationId = 60, StationNumber = 9244, StationName = "Navy Yard-Ballpark", Location = ("SE, Washington", "DC"), ParkingAvailable = false, BikeRacks = 14 };
                Stations[60] = new MetroStation() { StationId = 61, StationNumber = 1660, StationName = "Rockville", Location = ("Rockville", "MD"), ParkingAvailable = true, BikeRacks = 60 };
                Stations[61] = new MetroStation() { StationId = 62, StationNumber = 4244, StationName = "Deanwood", Location = ("NE, Washington", "DC"), ParkingAvailable = true, BikeRacks = 6 };
                Stations[62] = new MetroStation() { StationId = 63, StationNumber = 9485, StationName = "Ronald Reagan Washington National Airport", Location = ("Arlington", "VA"), ParkingAvailable = false, BikeRacks = 18 };
                Stations[63] = new MetroStation() { StationId = 64, StationNumber = 3973, StationName = "Potomac Ave", Location = ("SE, Washington", "DC"), ParkingAvailable = false, BikeRacks = 10 };
                Stations[64] = new MetroStation() { StationId = 65, StationNumber = 7385, StationName = "North Bethesda", Location = ("North Bethesda", "MD"), ParkingAvailable = true, BikeRacks = 16 };
                Stations[65] = new MetroStation() { StationId = 66, StationNumber = 1857, StationName = "Court House", Location = ("Arlington", "VA"), ParkingAvailable = false, BikeRacks = 25 };
                Stations[66] = new MetroStation() { StationId = 67, StationNumber = 3860, StationName = "Takoma", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 7 };
                Stations[67] = new MetroStation() { StationId = 68, StationNumber = 6483, StationName = "Branch Ave", Location = ("Suitland", "MD"), ParkingAvailable = true, BikeRacks = 10 };
                Stations[68] = new MetroStation() { StationId = 69, StationNumber = 9751, StationName = "Herndon", Location = ("Herndon", "VA"), ParkingAvailable = true, BikeRacks = 162 };
                Stations[69] = new MetroStation() { StationId = 70, StationNumber = 2927, StationName = "Farragut North", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[70] = new MetroStation() { StationId = 71, StationNumber = 8463, StationName = "Southern Avenue", Location = ("Hillcrest Heights", "MD"), ParkingAvailable = true, BikeRacks = 9 };
                Stations[71] = new MetroStation() { StationId = 72, StationNumber = 3366, StationName = "Washington Dulles International Airport", Location = ("Dulles", "VA"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[72] = new MetroStation() { StationId = 73, StationNumber = 2058, StationName = "Anacostia", Location = ("SE, Washington", "DC"), ParkingAvailable = true, BikeRacks = 8 };
                Stations[73] = new MetroStation() { StationId = 74, StationNumber = 2858, StationName = "Dunn Loring-Merrifield", Location = ("Vienna", "VA"), ParkingAvailable = true, BikeRacks = 49 };
                Stations[74] = new MetroStation() { StationId = 75, StationNumber = 2837, StationName = "Glenmont", Location = ("Silver Spring", "MD"), ParkingAvailable = true, BikeRacks = 25 };
                Stations[75] = new MetroStation() { StationId = 76, StationNumber = 1818, StationName = "Eastern Market", Location = ("SE, Washington", "DC"), ParkingAvailable = false, BikeRacks = 20 };
                Stations[76] = new MetroStation() { StationId = 77, StationNumber = 4174, StationName = "Virginia Square-GMU", Location = ("Arlington", "VA"), ParkingAvailable = false, BikeRacks = 12 };
                Stations[77] = new MetroStation() { StationId = 78, StationNumber = 4844, StationName = "Bethesda", Location = ("Bethesda", "MD"), ParkingAvailable = false, BikeRacks = 38 };
                Stations[78] = new MetroStation() { StationId = 79, StationNumber = 1827, StationName = "Rhode Island Ave-Brentwood", Location = ("NE, Washington", "DC"), ParkingAvailable = true, BikeRacks = 20 };
                Stations[79] = new MetroStation() { StationId = 80, StationNumber = 9479, StationName = "Hyattsville Crossing", Location = ("Hyattsville", "MD"), ParkingAvailable = true, BikeRacks = 32 };
                Stations[80] = new MetroStation() { StationId = 81, StationNumber = 3000, StationName = "Capitol South", Location = ("SE, Washington", "DC"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[81] = new MetroStation() { StationId = 82, StationNumber = 6622, StationName = "Greensboro", Location = ("Vienna", "VA"), ParkingAvailable = false, BikeRacks = 20 };
                Stations[82] = new MetroStation() { StationId = 83, StationNumber = 2022, StationName = "Federal Triangle", Location = ("NW, Washington ", "DC"), ParkingAvailable = false, BikeRacks = 0 };
                Stations[83] = new MetroStation() { StationId = 84, StationNumber = 9357, StationName = "Addison Road-Seat Pleasant", Location = ("Capitol Heights", "MD"), ParkingAvailable = true, BikeRacks = 8 };
                Stations[84] = new MetroStation() { StationId = 85, StationNumber = 6924, StationName = "Foggy Bottom-GWU", Location = ("NW, Washington ", "DC"), ParkingAvailable = false, BikeRacks = 10 };
                Stations[85] = new MetroStation() { StationId = 86, StationNumber = 2862, StationName = "Vienna/Fairfax-GMU", Location = ("Fairfax", "VA"), ParkingAvailable = true, BikeRacks = 86 };
                Stations[86] = new MetroStation() { StationId = 87, StationNumber = 2080, StationName = "Columbia Heights", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 15 };
                Stations[87] = new MetroStation() { StationId = 88, StationNumber = 7707, StationName = "Forest Glen", Location = ("Silver Spring ", "MD"), ParkingAvailable = true, BikeRacks = 49 };
                Stations[88] = new MetroStation() { StationId = 89, StationNumber = 5359, StationName = "Tysons", Location = ("McLean", "VA"), ParkingAvailable = false, BikeRacks = 28 };
                Stations[89] = new MetroStation() { StationId = 90, StationNumber = 7722, StationName = "U Street/African-Amer Civil War Memorial/Cardozo", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 8 };
                Stations[90] = new MetroStation() { StationId = 91, StationNumber = 2008, StationName = "Landover", Location = ("Landover", "MD"), ParkingAvailable = true, BikeRacks = 9 };
                Stations[91] = new MetroStation() { StationId = 92, StationNumber = 2957, StationName = "Cleveland Park", Location = ("NW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 8 };
                Stations[92] = new MetroStation() { StationId = 93, StationNumber = 8174, StationName = "Loudoun Gateway", Location = ("Ashburn", "VA"), ParkingAvailable = true, BikeRacks = 113 };
                Stations[93] = new MetroStation() { StationId = 94, StationNumber = 4826, StationName = "Smithsonian", Location = ("SW, Washington", "DC"), ParkingAvailable = false, BikeRacks = 2 };
                Stations[94] = new MetroStation() { StationId = 95, StationNumber = 2205, StationName = "Van Dorn Street", Location = ("Alexandria", "VA"), ParkingAvailable = true, BikeRacks = 30 };
                Stations[95] = new MetroStation() { StationId = 96, StationNumber = 9486, StationName = "Morgan Boulevard", Location = ("Landover", "MD"), ParkingAvailable = true, BikeRacks = 14 };
                Stations[96] = new MetroStation() { StationId = 97, StationNumber = 4925, StationName = "Spring Hill", Location = ("Vienna", "VA"), ParkingAvailable = false, BikeRacks = 10 };
                Stations[97] = new MetroStation() { StationId = 98, StationNumber = 2739, StationName = "Stadium-Armory", Location = ("SE, Washington", "DC"), ParkingAvailable = false, BikeRacks = 7 };
    
                Lines[0] = new MetroLine(1, "Green", 1862, 6483);
                Lines[1] = new MetroLine(LineName: "Red", LineId: 2, Between: 2014, And: 2837);
                Lines[2] = new(3, "Yellow", 6866, 3383);
                Lines[3] = new(LineId: 4, LineName: "Blue", Between: 3975, And: 2859);
                Lines[4] = new MetroLine(LineName: "Orange", LineId: 5, Between: 6866, And: 3383);
                Lines[5] = new MetroLine(LineName: "Silver", Between: 3975, And: 9393, LineId: 6);
    
                StationsAndLines[0]   = new StationAndLine(LinedStationId:   1, StationNumber: 1862, LineName: "Green");    // Greenbelt
                StationsAndLines[1]   = new StationAndLine(LinedStationId:   2, StationNumber: 9537, LineName: "Green");    // College Park-U of Md
                StationsAndLines[2]   = new StationAndLine(LinedStationId:   3, StationNumber: 9479, LineName: "Green");    // Hyattsville Crossing
                StationsAndLines[3]   = new StationAndLine(LinedStationId:   4, StationNumber: 7597, LineName: "Green");    // West Hyattsville
                StationsAndLines[4]   = new StationAndLine(LinedStationId:   5, StationNumber: 9794, LineName: "Green");    // Fort Totten
                StationsAndLines[5]   = new StationAndLine(LinedStationId:   6, StationNumber: 4836, LineName: "Green");    // Georgia Ave-Petworth
                StationsAndLines[6]   = new StationAndLine(LinedStationId:   7, StationNumber: 2080, LineName: "Green");    // Columbia Heights
                StationsAndLines[7]   = new StationAndLine(LinedStationId:   8, StationNumber: 7722, LineName: "Green");    // U Street/African-Amer Civil War Memorial/Cardozo
                StationsAndLines[8]   = new StationAndLine(LinedStationId:   9, StationNumber: 4975, LineName: "Green");    // Shaw-Howard U
                StationsAndLines[9]   = new StationAndLine(LinedStationId:  10, StationNumber: 6866, LineName: "Green");    // Mt Vernon Sq 7th St-Convention Center
                StationsAndLines[10]  = new StationAndLine(LinedStationId:  11, StationNumber: 3584, LineName: "Green");    // Gallery Place Chinatown
                StationsAndLines[11]  = new StationAndLine(LinedStationId:  12, StationNumber: 1486, LineName: "Green");    // Archives-Navy Memorial-Penn Quarter
                StationsAndLines[12]  = new StationAndLine(LinedStationId:  13, StationNumber: 3947, LineName: "Green");    // L'Enfant Plaza
                StationsAndLines[13]  = new StationAndLine(LinedStationId:  14, StationNumber: 8263, LineName: "Green");    // Waterfront
                StationsAndLines[14]  = new StationAndLine(LinedStationId:  15, StationNumber: 9244, LineName: "Green");    // Navy Yard-Ballpark
                StationsAndLines[15]  = new StationAndLine(LinedStationId:  16, StationNumber: 2058, LineName: "Green");    // Anacostia
                StationsAndLines[16]  = new StationAndLine(LinedStationId:  17, StationNumber: 9374, LineName: "Green");    // Congress Heights
                StationsAndLines[17]  = new StationAndLine(LinedStationId:  18, StationNumber: 8463, LineName: "Green");    // Southern Avenue
                StationsAndLines[18]  = new StationAndLine(LinedStationId:  19, StationNumber: 8473, LineName: "Green");    // Naylor Road
                StationsAndLines[19]  = new StationAndLine(LinedStationId:  20, StationNumber: 1155, LineName: "Green");    // Suitland
                StationsAndLines[20]  = new StationAndLine(LinedStationId:  21, StationNumber: 6483, LineName: "Green");    // Branch Ave
    
                StationsAndLines[21]  = new StationAndLine(LinedStationId:  22, StationNumber: 6866, LineName: "Yellow");   // Mt Vernon Sq 7th St-Convention Center
                StationsAndLines[22]  = new StationAndLine(LinedStationId:  23, StationNumber: 3584, LineName: "Yellow");   // Gallery Place Chinatown
                StationsAndLines[23]  = new StationAndLine(LinedStationId:  24, StationNumber: 1486, LineName: "Yellow");   // Archives-Navy Memorial-Penn Quarter
                StationsAndLines[24]  = new StationAndLine(LinedStationId:  25, StationNumber: 3947, LineName: "Yellow");   // L'Enfant Plaza
                StationsAndLines[25]  = new StationAndLine(LinedStationId:  26, StationNumber: 3974, LineName: "Yellow");   // Pentagon
                StationsAndLines[26]  = new StationAndLine(LinedStationId:  27, StationNumber: 6470, LineName: "Yellow");   // Pentagon City
                StationsAndLines[27]  = new StationAndLine(LinedStationId:  28, StationNumber: 8684, LineName: "Yellow");   // Crystal City
                StationsAndLines[28]  = new StationAndLine(LinedStationId:  29, StationNumber: 9485, LineName: "Yellow");   // Ronald Reagan Washington National Airport
                StationsAndLines[29]  = new StationAndLine(LinedStationId:  30, StationNumber: 4084, LineName: "Yellow");   // Potomac Yard
                StationsAndLines[30]  = new StationAndLine(LinedStationId:  31, StationNumber: 1575, LineName: "Yellow");   // Braddock Road
                StationsAndLines[31]  = new StationAndLine(LinedStationId:  32, StationNumber: 5592, LineName: "Yellow");   // King St-Old Town
                StationsAndLines[32]  = new StationAndLine(LinedStationId:  33, StationNumber: 8686, LineName: "Yellow");   // Eisenhower Avenue
                StationsAndLines[33]  = new StationAndLine(LinedStationId:  34, StationNumber: 3383, LineName: "Yellow");   // Huntington
    
                StationsAndLines[34]  = new StationAndLine(LinedStationId:  35, StationNumber: 2014, LineName: "Red");      // Shady Grove
                StationsAndLines[35]  = new StationAndLine(LinedStationId:  36, StationNumber: 1660, LineName: "Red");      // Rockville
                StationsAndLines[36]  = new StationAndLine(LinedStationId:  37, StationNumber: 6497, LineName: "Red");      // Twinbrook
                StationsAndLines[37]  = new StationAndLine(LinedStationId:  38, StationNumber: 7385, LineName: "Red");      // North Bethesda
                StationsAndLines[38]  = new StationAndLine(LinedStationId:  39, StationNumber: 5739, LineName: "Red");      // Grosvenor-Strathmore
                StationsAndLines[39]  = new StationAndLine(LinedStationId:  40, StationNumber: 9795, LineName: "Red");      // Medical Center
                StationsAndLines[40]  = new StationAndLine(LinedStationId:  41, StationNumber: 4844, LineName: "Red");      // Bethesda
                StationsAndLines[41]  = new StationAndLine(LinedStationId:  42, StationNumber: 7468, LineName: "Red");      // Friendship Heights
                StationsAndLines[42]  = new StationAndLine(LinedStationId:  43, StationNumber: 1770, LineName: "Red");      // Tenleytown-AU
                StationsAndLines[43]  = new StationAndLine(LinedStationId:  44, StationNumber: 2493, LineName: "Red");      // Van Ness-UDC
                StationsAndLines[44]  = new StationAndLine(LinedStationId:  45, StationNumber: 2957, LineName: "Red");      // Cleveland Park
                StationsAndLines[45]  = new StationAndLine(LinedStationId:  46, StationNumber: 2969, LineName: "Red");      // Woodley Park-Zoo/Adams Morgan
                StationsAndLines[46]  = new StationAndLine(LinedStationId:  47, StationNumber: 5575, LineName: "Red");      // Dupont Circle
                StationsAndLines[47]  = new StationAndLine(LinedStationId:  48, StationNumber: 2927, LineName: "Red");      // Farragut North
                StationsAndLines[48]  = new StationAndLine(LinedStationId:  49, StationNumber: 4480, LineName: "Red");      // Metro Center
                StationsAndLines[49]  = new StationAndLine(LinedStationId:  50, StationNumber: 3584, LineName: "Red");      // Gallery Place Chinatown
                StationsAndLines[50]  = new StationAndLine(LinedStationId:  51, StationNumber: 5947, LineName: "Red");      // Judiciary Square
                StationsAndLines[51]  = new StationAndLine(LinedStationId:  52, StationNumber: 7720, LineName: "Red");      // Union Station
                StationsAndLines[52]  = new StationAndLine(LinedStationId:  53, StationNumber: 5248, LineName: "Red");      // NoMa-Gallaudet U
                StationsAndLines[53]  = new StationAndLine(LinedStationId:  54, StationNumber: 1827, LineName: "Red");      // Rhode Island Ave-Brentwood
                StationsAndLines[54]  = new StationAndLine(LinedStationId:  55, StationNumber: 3330, LineName: "Red");      // Brookland-CUA
                StationsAndLines[55]  = new StationAndLine(LinedStationId:  56, StationNumber: 9794, LineName: "Red");      // Fort Totten
                StationsAndLines[56]  = new StationAndLine(LinedStationId:  57, StationNumber: 3860, LineName: "Red");      // Takoma
                StationsAndLines[57]  = new StationAndLine(LinedStationId:  58, StationNumber: 1475, LineName: "Red");      // Silver Spring
                StationsAndLines[58]  = new StationAndLine(LinedStationId:  59, StationNumber: 7707, LineName: "Red");      // Forest Glen
                StationsAndLines[59]  = new StationAndLine(LinedStationId:  60, StationNumber: 6295, LineName: "Red");      // Wheaton
                StationsAndLines[60]  = new StationAndLine(LinedStationId:  61, StationNumber: 2837, LineName: "Red");      // Glenmont
    
                StationsAndLines[61]  = new StationAndLine(LinedStationId:  62, StationNumber: 3975, LineName: "Blue");     // Downtown Largo
                StationsAndLines[62]  = new StationAndLine(LinedStationId:  63, StationNumber: 9486, LineName: "Blue");     // Morgan Blvd
                StationsAndLines[63]  = new StationAndLine(LinedStationId:  64, StationNumber: 9357, LineName: "Blue");     // Addison Road
                StationsAndLines[64]  = new StationAndLine(LinedStationId:  65, StationNumber: 8374, LineName: "Blue");     // Capitol Heights
                StationsAndLines[65]  = new StationAndLine(LinedStationId:  66, StationNumber: 2082, LineName: "Blue");     // Benning Road
                StationsAndLines[66]  = new StationAndLine(LinedStationId:  67, StationNumber: 2739, LineName: "Blue");     // Stadium-Armory
                StationsAndLines[67]  = new StationAndLine(LinedStationId:  68, StationNumber: 3973, LineName: "Blue");     // Potomac Ave
                StationsAndLines[68]  = new StationAndLine(LinedStationId:  69, StationNumber: 1818, LineName: "Blue");     // Eastern Market
                StationsAndLines[69]  = new StationAndLine(LinedStationId:  70, StationNumber: 3000, LineName: "Blue");     // Capitol South
                StationsAndLines[70]  = new StationAndLine(LinedStationId:  71, StationNumber: 9475, LineName: "Blue");     // Federal Center SW
                StationsAndLines[71]  = new StationAndLine(LinedStationId:  72, StationNumber: 3947, LineName: "Blue");     // L'Enfant Plaza
                StationsAndLines[72]  = new StationAndLine(LinedStationId:  73, StationNumber: 4826, LineName: "Blue");     // Smithsonian
                StationsAndLines[73]  = new StationAndLine(LinedStationId:  74, StationNumber: 2022, LineName: "Blue");     // Federal Triangle
                StationsAndLines[74]  = new StationAndLine(LinedStationId:  75, StationNumber: 4480, LineName: "Blue");     // Metro Center
                StationsAndLines[75]  = new StationAndLine(LinedStationId:  76, StationNumber: 5395, LineName: "Blue");     // McPherson Square
                StationsAndLines[76]  = new StationAndLine(LinedStationId:  77, StationNumber: 7118, LineName: "Blue");     // Farragut West
                StationsAndLines[77]  = new StationAndLine(LinedStationId:  78, StationNumber: 6924, LineName: "Blue");     // Foggy Bottom-GWU
                StationsAndLines[78]  = new StationAndLine(LinedStationId:  79, StationNumber: 2841, LineName: "Blue");     // Rosslyn
                StationsAndLines[79]  = new StationAndLine(LinedStationId:  80, StationNumber: 8486, LineName: "Blue");     // Arlington Cemetery
                StationsAndLines[80]  = new StationAndLine(LinedStationId:  81, StationNumber: 3974, LineName: "Blue");     // Pentagon
                StationsAndLines[81]  = new StationAndLine(LinedStationId:  82, StationNumber: 6470, LineName: "Blue");     // Pentagon City
                StationsAndLines[82]  = new StationAndLine(LinedStationId:  83, StationNumber: 8684, LineName: "Blue");     // Crystal City
                StationsAndLines[83]  = new StationAndLine(LinedStationId:  84, StationNumber: 9485, LineName: "Blue");     // Ronald Reagan Washington National Airport
                StationsAndLines[84]  = new StationAndLine(LinedStationId:  85, StationNumber: 4084, LineName: "Blue");     // Potomac Yard
                StationsAndLines[85]  = new StationAndLine(LinedStationId:  86, StationNumber: 1575, LineName: "Blue");     // Braddock Road
                StationsAndLines[86]  = new StationAndLine(LinedStationId:  87, StationNumber: 5592, LineName: "Blue");     // King St-Old Town
                StationsAndLines[87]  = new StationAndLine(LinedStationId:  88, StationNumber: 2205, LineName: "Blue");     // Van Dorn Street
                StationsAndLines[88]  = new StationAndLine(LinedStationId:  89, StationNumber: 2859, LineName: "Blue");     // Franconia-Springfield
    
                StationsAndLines[89]  = new StationAndLine(LinedStationId:  90, StationNumber: 6083, LineName: "Orange");   // New Carrollton
                StationsAndLines[90]  = new StationAndLine(LinedStationId:  91, StationNumber: 2008, LineName: "Orange");   // Landover
                StationsAndLines[91]  = new StationAndLine(LinedStationId:  92, StationNumber: 2938, LineName: "Orange");   // Cheverly
                StationsAndLines[92]  = new StationAndLine(LinedStationId:  93, StationNumber: 4244, LineName: "Orange");   // Deanwood
                StationsAndLines[93]  = new StationAndLine(LinedStationId:  94, StationNumber: 3815, LineName: "Orange");   // Minnesota Ave
                StationsAndLines[94]  = new StationAndLine(LinedStationId:  95, StationNumber: 2739, LineName: "Orange");   // Stadium-Armory
                StationsAndLines[95]  = new StationAndLine(LinedStationId:  96, StationNumber: 3973, LineName: "Orange");   // Potomac Ave
                StationsAndLines[96]  = new StationAndLine(LinedStationId:  97, StationNumber: 1818, LineName: "Orange");   // Eastern Market
                StationsAndLines[97]  = new StationAndLine(LinedStationId:  98, StationNumber: 3000, LineName: "Orange");   // Capitol South
                StationsAndLines[98]  = new StationAndLine(LinedStationId:  99, StationNumber: 9475, LineName: "Orange");   // Federal Center SW
                StationsAndLines[99]  = new StationAndLine(LinedStationId: 100, StationNumber: 3947, LineName: "Orange");   // L'Enfant Plaza
                StationsAndLines[100] = new StationAndLine(LinedStationId: 101, StationNumber: 4826, LineName: "Orange");   // Smithsonian
                StationsAndLines[101] = new StationAndLine(LinedStationId: 102, StationNumber: 2022, LineName: "Orange");   // Federal Triangle
                StationsAndLines[102] = new StationAndLine(LinedStationId: 103, StationNumber: 4480, LineName: "Orange");   // Metro Center
                StationsAndLines[103] = new StationAndLine(LinedStationId: 104, StationNumber: 5395, LineName: "Orange");   // McPherson Square
                StationsAndLines[104] = new StationAndLine(LinedStationId: 105, StationNumber: 7118, LineName: "Orange");   // Farragut West
                StationsAndLines[105] = new StationAndLine(LinedStationId: 106, StationNumber: 6924, LineName: "Orange");   // Foggy Bottom-GWU
                StationsAndLines[106] = new StationAndLine(LinedStationId: 107, StationNumber: 2841, LineName: "Orange");   // Rosslyn
                StationsAndLines[107] = new StationAndLine(LinedStationId: 108, StationNumber: 1857, LineName: "Orange");   // Court House
                StationsAndLines[108] = new StationAndLine(LinedStationId: 109, StationNumber: 7497, LineName: "Orange");   // Clarendon
                StationsAndLines[109] = new StationAndLine(LinedStationId: 110, StationNumber: 4174, LineName: "Orange");   // Virginia Square-GMU
                StationsAndLines[110] = new StationAndLine(LinedStationId: 111, StationNumber: 8111, LineName: "Orange");   // Ballston-MU
                StationsAndLines[111] = new StationAndLine(LinedStationId: 112, StationNumber: 1584, LineName: "Orange");   // East Falls Church
                StationsAndLines[112] = new StationAndLine(LinedStationId: 113, StationNumber: 5022, LineName: "Orange");   // West Falls Church
                StationsAndLines[113] = new StationAndLine(LinedStationId: 114, StationNumber: 2858, LineName: "Orange");   // Dunn Loring-Merrifield
                StationsAndLines[114] = new StationAndLine(LinedStationId: 115, StationNumber: 2862, LineName: "Orange");   // Vienna/Fairfax-GMU
    
                StationsAndLines[115] = new StationAndLine(LinedStationId: 116, StationNumber: 3975, LineName: "Silver");   // Downtown Largo
                StationsAndLines[116] = new StationAndLine(LinedStationId: 117, StationNumber: 9486, LineName: "Silver");   // Morgan Blvd
                StationsAndLines[117] = new StationAndLine(LinedStationId: 118, StationNumber: 9357, LineName: "Silver");   // Addison Road
                StationsAndLines[118] = new StationAndLine(LinedStationId: 119, StationNumber: 8374, LineName: "Silver");   // Capitol Heights
                StationsAndLines[119] = new StationAndLine(LinedStationId: 120, StationNumber: 2082, LineName: "Silver");   // Benning Road
    
                StationsAndLines[120] = new StationAndLine(LinedStationId: 121, StationNumber: 6083, LineName: "Silver");   // New Carrollton
                StationsAndLines[121] = new StationAndLine(LinedStationId: 122, StationNumber: 2008, LineName: "Silver");   // Landover
                StationsAndLines[122] = new StationAndLine(LinedStationId: 123, StationNumber: 2938, LineName: "Silver");   // Cheverly
                StationsAndLines[123] = new StationAndLine(LinedStationId: 124, StationNumber: 4244, LineName: "Silver");   // Deanwood
                StationsAndLines[124] = new StationAndLine(LinedStationId: 125, StationNumber: 3815, LineName: "Silver");   // Minnesota Ave
    
                StationsAndLines[125] = new StationAndLine(LinedStationId: 126, StationNumber: 2739, LineName: "Silver");   // Stadium-Armory
                StationsAndLines[126] = new StationAndLine(LinedStationId: 127, StationNumber: 3973, LineName: "Silver");   // Potomac Ave
                StationsAndLines[127] = new StationAndLine(LinedStationId: 128, StationNumber: 1818, LineName: "Silver");   // Eastern Market
                StationsAndLines[128] = new StationAndLine(LinedStationId: 129, StationNumber: 3000, LineName: "Silver");   // Capitol South
                StationsAndLines[129] = new StationAndLine(LinedStationId: 130, StationNumber: 9475, LineName: "Silver");   // Federal Center SW
                StationsAndLines[130] = new StationAndLine(LinedStationId: 131, StationNumber: 3947, LineName: "Silver");   // L'Enfant Plaza
                StationsAndLines[131] = new StationAndLine(LinedStationId: 132, StationNumber: 4826, LineName: "Silver");   // Smithsonian
                StationsAndLines[132] = new StationAndLine(LinedStationId: 133, StationNumber: 2022, LineName: "Silver");   // Federal Triangle
                StationsAndLines[133] = new StationAndLine(LinedStationId: 134, StationNumber: 4480, LineName: "Silver");   // Metro Center
                StationsAndLines[134] = new StationAndLine(LinedStationId: 135, StationNumber: 5395, LineName: "Silver");   // McPherson Square
                StationsAndLines[135] = new StationAndLine(LinedStationId: 136, StationNumber: 7118, LineName: "Silver");   // Farragut West
                StationsAndLines[136] = new StationAndLine(LinedStationId: 137, StationNumber: 6924, LineName: "Silver");   // Foggy Bottom-GWU
                StationsAndLines[137] = new StationAndLine(LinedStationId: 138, StationNumber: 2841, LineName: "Silver");   //  Rosslyn
                StationsAndLines[138] = new StationAndLine(LinedStationId: 139, StationNumber: 1857, LineName: "Silver");   // Court House
                StationsAndLines[139] = new StationAndLine(LinedStationId: 140, StationNumber: 7497, LineName: "Silver");   // Clarendon
                StationsAndLines[140] = new StationAndLine(LinedStationId: 141, StationNumber: 4174, LineName: "Silver");   // Virginia Square-GMU
                StationsAndLines[141] = new StationAndLine(LinedStationId: 142, StationNumber: 8111, LineName: "Silver");   // Ballston-MU
                StationsAndLines[142] = new StationAndLine(LinedStationId: 143, StationNumber: 1584, LineName: "Silver");   // East Falls Church
                StationsAndLines[143] = new StationAndLine(LinedStationId: 144, StationNumber: 7946, LineName: "Silver");   // McLean
                StationsAndLines[144] = new StationAndLine(LinedStationId: 145, StationNumber: 5359, LineName: "Silver");   // Tysons
                StationsAndLines[145] = new StationAndLine(LinedStationId: 146, StationNumber: 6622, LineName: "Silver");   // Greensboro
                StationsAndLines[146] = new StationAndLine(LinedStationId: 147, StationNumber: 4925, LineName: "Silver");   // Spring Hill
                StationsAndLines[147] = new StationAndLine(LinedStationId: 148, StationNumber: 2860, LineName: "Silver");   // Wiehle-Reston East
                StationsAndLines[148] = new StationAndLine(LinedStationId: 149, StationNumber: 9638, LineName: "Silver");   // Reston Town Center
                StationsAndLines[149] = new StationAndLine(LinedStationId: 150, StationNumber: 9751, LineName: "Silver");   // Herndon
                StationsAndLines[150] = new StationAndLine(LinedStationId: 151, StationNumber: 5297, LineName: "Silver");   // Innovation Center
                StationsAndLines[151] = new StationAndLine(LinedStationId: 152, StationNumber: 3366, LineName: "Silver");   // Washington Dulles International Airport
                StationsAndLines[152] = new StationAndLine(LinedStationId: 153, StationNumber: 8174, LineName: "Silver");   // Loudoun Gateway
                StationsAndLines[153] = new StationAndLine(LinedStationId: 154, StationNumber: 9393, LineName: "Silver");   // Ashburn
            }
        }
    }

Constant Fields and Static Types

If you have a value that is accessed in different parts of your project, you can create a constant for that value in a class. If you have many values that follow that scenario, you can create their constants in a class. Wherever the constant is needed throughout your project, you can access it from its class. In this description, you would have to declare a variable of the class and then access the constant from that variable. To make it a little easier to access the constant, a good technique is to create the class as a static one. If you do that, you can access the constant by using the name of the class.

Practical LearningPractical Learning: Creating Global Constants

  1. To create a class, in the Solution Explorer, right-click Models -> Add -> Class
  2. Type RoutineConstants as the name of the class
  3. Click Add
  4. Change the document as follows:
    namespace MetropolitanTransitSystem2.Models
    {
        internal static class RoutineConstants
        {
            public const string LineTitle           = "Metro Line";
            public const string LinesTitle          = "Metro Lines";
            public const string StationsTitle       = "Metro Stations";
            public const string ApplicationTitle    = "Metropolitan Area Transit Authority";
            public const string LinesAnswerError    = "The value you typed cannot identify a metro line.";
            public const string DoubleLine          = "====================================================================";
            public const string SingleLine          = "--------------------------------------------------------------------";
            public const string IntroductoryMessage = "This application is meant to assist metro commuters and metropolitan \n" +
                                                      "area visitors. From this application, a user can see a list of metro \n" +
                                                      "lines or a list of all metro stations. A user can also select a metro \n" +
                                                      "line and get a list of the metro stations on that particular metro \n" +
                                                      "line. A user can also get detailed information about a metro line \n" +
                                                      "or a metro station. A user can also enquire on how to get to a \n" + 
                                                      "popular point of interest.";
        }
    }
  5. In the Solution Explorer, double-click Program.cs to access the main file of the application
  6. Change the document as follows:
    using static System.Console;
    using MetropolitanTransitSystem10.Models;
    
    WriteLine(RoutineConstants.ApplicationTitle);
    WriteLine(RoutineConstants.DoubleLine);
    WriteLine(RoutineConstants.IntroductoryMessage);
    
    Database db = new();
    string? actionSelection = string.Empty;
    
    do
    {
        WriteLine(RoutineConstants.DoubleLine);
        WriteLine("What do you want to do?");
        WriteLine("1 - See a list of metro lines.");
        WriteLine("2 - See a list of all metro stations.");
        WriteLine("3 - Select a metro line and see its metro stations.");
        WriteLine("0 - Exit.");
        Write("Enter your selection: ");
        actionSelection = ReadLine()!;
    
        switch (actionSelection)
        {
            case "1":
                ShowMetroLines();
                break;
            case "2":
                ShowMetroStations();
                break;
            case "3":
                SelectMetroLine();
                break;
            default:
                WriteLine(RoutineConstants.DoubleLine);
                WriteLine("Goodbye");
                break;
        }
    } while ((actionSelection == "1") || (actionSelection == "2") || (actionSelection == "3"));
    
    void SelectMetroLine()
    {
        Clear();
    
        WriteLine(RoutineConstants.ApplicationTitle);
        WriteLine(RoutineConstants.DoubleLine);
        WriteLine(RoutineConstants.LinesTitle);
        WriteLine(RoutineConstants.SingleLine);
    
        int i = 0;
    
        while (true)
        {
            WriteLine("{0} - {1}", db.Lines[i].LineId, db.Lines[i].LineName);
    
            if (i == db.Lines.Length - 1)
            { break; }
            i++;
        }
    
        WriteLine(RoutineConstants.DoubleLine);
    
        Write("Show the list of metro stations on Line: ");
        string strLine = ReadLine()!;
    
        switch (strLine.ToLower())
        {
            case "1":
            case "green":
                ShowMetroLine("Green");
                break;
    
            case "2":
            case "red":
                ShowMetroLine("Red");
                break;
    
            case "3":
            case "yellow":
                ShowMetroLine("Yellow");
                break;
    
            case "4":
            case "blue":
                ShowMetroLine("Blue");
                break;
    
            case "5":
            case "orange":
                ShowMetroLine("Orange");
                break;
    
            case "6":
            case "silver":
                ShowMetroLine("Silver");
                break;
    
            default:
                WriteLine(RoutineConstants.DoubleLine);
                WriteLine(RoutineConstants.LinesAnswerError);
                break;
        }
    }
    
    WriteLine(RoutineConstants.DoubleLine);
    
    void ShowMetroLines()
    {
        Clear();
    
        WriteLine(RoutineConstants.ApplicationTitle);
        WriteLine(RoutineConstants.DoubleLine);
        WriteLine(RoutineConstants.LinesTitle);
        WriteLine(RoutineConstants.SingleLine);
    
        int i = 1;
    
        foreach (MetroLine line in db.Lines)
        {
            WriteLine("{0} - {1}", i++, line.LineName);
        }
    }
    
    void ShowMetroStations()
    {
        Clear();
    
        WriteLine(RoutineConstants.ApplicationTitle);
        WriteLine(RoutineConstants.DoubleLine);
        WriteLine(RoutineConstants.StationsTitle);
        WriteLine(RoutineConstants.SingleLine);
    
        int i = 1;
    
        foreach (MetroStation station in db.Stations)
        {
            WriteLine("{0}:\t{1} - {2}, {3}", i++, station.StationNumber, station.StationName, station.Location);
        }
    }
    
    void ShowMetroLine(string color)
    {
        Clear();
    
        WriteLine(RoutineConstants.ApplicationTitle);
        WriteLine(RoutineConstants.DoubleLine);
        WriteLine(RoutineConstants.StationsTitle);
        WriteLine(RoutineConstants.SingleLine);
    
        int i = 1;
    
        Write(RoutineConstants.LineTitle + " - ");
    
        foreach (MetroLine line in db.Lines)
        {
            if (line.LineName == color)
            {
                WriteLine(line.LineName);
            }
        }
    
        WriteLine(RoutineConstants.SingleLine);
    
        foreach (StationAndLine sal in db.StationsAndLines)
        {
            if (sal.LineName == color)
            {
                foreach (MetroStation ms in db.Stations)
                {
                    if (ms.StationNumber == sal.StationNumber)
                    {
                        WriteLine("{0}\t- {1} {2}", i++, sal.StationNumber, ms.StationName);
                    }
                }
            }
        }
    }
  7. To execute the project, on the main menu, click Debug -> Start Without Debugging:
    Metropolitan Area Transit Authority
    ====================================================================
    This application is meant to assist metro commuters and metropolitan
    area visitors. From this application, a user can see a list of metro
    lines or a list of all metro stations. A user can also select a metro
    line and get a list of the metro stations on that particular metro
    line. A user can also get detailed information about a metro line
    or a metro station. A user can also enquire on how to get to a
    popular point of interest.
    ====================================================================
    What do you want to do?
    1 - See a list of metro lines.
    2 - See a list of all metro stations.
    3 - Select a metro line and see its metro stations.
    0 - Exit.
    Enter your selection:
  8. On the menu, type 1 and press Enter:
    Metropolitan Area Transit Authority
    ====================================================================
    Metro Lines
    --------------------------------------------------------------------
    1 - Green
    2 - Red
    3 - Yellow
    4 - Blue
    5 - Orange
    6 - Silver
    ====================================================================
    What do you want to do?
    1 - See a list of metro lines.
    2 - See a list of all metro stations.
    3 - Select a metro line and see its metro stations.
    0 - Exit.
    Enter your selection:
  9. On the menu, type 2 and press Enter:
    Metropolitan Area Transit Authority
    ====================================================================
    Metro Stations
    --------------------------------------------------------------------
    1:      9374 - Congress Heights, (SE, Washington, DC)
    2:      2859 - Franconia-Springfield, (Springfield, VA)
    3:      6083 - New Carrollton, (New Carrollton, MD)
    4:      4480 - Metro Center, (NW, Washington , DC)
    5:      1584 - East Falls Church, (Arlington, VA)
    6:      6295 - Wheaton, (Wheaton, MD)
    7:      3815 - Minnesota Ave, (NE, Washington , DC)
    8:      8684 - Crystal City, (Arlington, VA)
    9:      5248 - NoMa-Gallaudet U, (NE, Washington, DC)
    10:     9393 - Ashburn, (Ashburn, VA)
    11:     6497 - Twinbrook, (Rockville, MD)
    12:     2969 - Woodley Park-Zoo/Adams Morgan, (NW, Washington, DC)
    13:     8686 - Eisenhower Avenue, (Arlington, VA)
    14:     4836 - Georgia Ave-Petworth, (NW, Washington, DC)
    15:     2841 - Rosslyn, (Arlington, VA)
    16:     2082 - Benning Road, (NE, Washington, DC)
    17:     8486 - Arlington Cemetery, (Arlington, VA)
    18:     5575 - Dupont Circle, (NW, Washington, DC)
    19:     9638 - Reston Town Center, (Reston, VA)
    20:     3584 - Gallery Place Chinatown, (NW, Washington, DC)
    21:     7597 - West Hyattsville, (Hyattsville, MD)
    22:     4975 - Shaw-Howard U, (NW, Washington, DC)
    23:     2014 - Shady Grove, (Rockville, MD)
    24:     5395 - McPherson Square, (NW, Washington, DC)
    25:     7497 - Clarendon, (Arlington, VA)
    26:     9794 - Fort Totten, (NE, Washington, DC)
    27:     3975 - Downtown Largo, (Largo, MD)
    28:     1575 - Braddock Road, (Alexandria, VA)
    29:     8473 - Naylor Road, (Hillcrest Heights, MD)
    30:     5297 - Innovation Center, (Herndon, VA)
    31:     7118 - Farragut West, (NW, Washington, DC)
    32:     1155 - Suitland, (Suitland, MD)
    33:     3330 - Brookland-CUA, (NE, Washington, DC)
    34:     5739 - Grosvenor-Strathmore, (North Bethesda, MD)
    35:     1486 - Archives-Navy Memorial-Penn Quarter, (NW, Washington, DC)
    36:     7946 - McLean, (McLean, VA)
    37:     2938 - Cheverly, (Cheverly, MD)
    38:     5947 - Judiciary Square, (NW, Washington, DC)
    39:     8111 - Ballston-MU, (Arlington, VA)
    40:     1770 - Tenleytown-AU, (NW, Washington, DC)
    41:     3974 - Pentagon, (Arlington, VA)
    42:     6866 - Mt Vernon Sq 7th St-Convention Center, (NW, Washington, DC)
    43:     8374 - Capitol Heights, (Capitol Heights, MD)
    44:     2493 - Van Ness-UDC, (NW, Washington, DC)
    45:     5592 - King St-Old Town, (Alexandria, VA)
    46:     7720 - Union Station, (NE, Washington, DC)
    47:     1862 - Greenbelt, (Beltsville, MD)
    48:     4084 - Potomac Yard, (Alexandria, VA)
    49:     9795 - Medical Center, (Bethesda, MD)
    50:     2860 - Wiehle-Reston East, (Reston, VA)
    51:     9475 - Federal Center SW, (SW, Washington, DC)
    52:     8263 - Waterfront, (SW, Washington, DC)
    53:     9537 - College Park-U of Md, (College Park, MD)
    54:     3383 - Huntington, (Alexandria, VA)
    55:     7468 - Friendship Heights, (NW, Washington, DC)
    56:     1475 - Silver Spring, (Silver Spring, MD)
    57:     5022 - West Falls Church, (Falls Church, VA)
    58:     3947 - L'Enfant Plaza, (SW, Washington, DC)
    59:     6470 - Pentagon City, (Arlington, VA)
    60:     9244 - Navy Yard-Ballpark, (SE, Washington, DC)
    61:     1660 - Rockville, (Rockville, MD)
    62:     4244 - Deanwood, (NE, Washington, DC)
    63:     9485 - Ronald Reagan Washington National Airport, (Arlington, VA)
    64:     3973 - Potomac Ave, (SE, Washington, DC)
    65:     7385 - North Bethesda, (North Bethesda, MD)
    66:     1857 - Court House, (Arlington, VA)
    67:     3860 - Takoma, (NW, Washington, DC)
    68:     6483 - Branch Ave, (Suitland, MD)
    69:     9751 - Herndon, (Herndon, VA)
    70:     2927 - Farragut North, (NW, Washington, DC)
    71:     8463 - Southern Avenue, (Hillcrest Heights, MD)
    72:     3366 - Washington Dulles International Airport, (Dulles, VA)
    73:     2058 - Anacostia, (SE, Washington, DC)
    74:     2858 - Dunn Loring-Merrifield, (Vienna, VA)
    75:     2837 - Glenmont, (Silver Spring, MD)
    76:     1818 - Eastern Market, (SE, Washington, DC)
    77:     4174 - Virginia Square-GMU, (Arlington, VA)
    78:     4844 - Bethesda, (Bethesda, MD)
    79:     1827 - Rhode Island Ave-Brentwood, (NE, Washington, DC)
    80:     9479 - Hyattsville Crossing, (Hyattsville, MD)
    81:     3000 - Capitol South, (SE, Washington, DC)
    82:     6622 - Greensboro, (Vienna, VA)
    83:     2022 - Federal Triangle, (NW, Washington , DC)
    84:     9357 - Addison Road-Seat Pleasant, (Capitol Heights, MD)
    85:     6924 - Foggy Bottom-GWU, (NW, Washington , DC)
    86:     2862 - Vienna/Fairfax-GMU, (Fairfax, VA)
    87:     2080 - Columbia Heights, (NW, Washington, DC)
    88:     7707 - Forest Glen, (Silver Spring , MD)
    89:     5359 - Tysons, (McLean, VA)
    90:     7722 - U Street/African-Amer Civil War Memorial/Cardozo, (NW, Washington, DC)
    91:     2008 - Landover, (Landover, MD)
    92:     2957 - Cleveland Park, (NW, Washington, DC)
    93:     8174 - Loudoun Gateway, (Ashburn, VA)
    94:     4826 - Smithsonian, (SW, Washington, DC)
    95:     2205 - Van Dorn Street, (Alexandria, VA)
    96:     9486 - Morgan Boulevard, (Landover, MD)
    97:     4925 - Spring Hill, (Vienna, VA)
    98:     2739 - Stadium-Armory, (SE, Washington, DC)
    ====================================================================
    What do you want to do?
    1 - See a list of metro lines.
    2 - See a list of all metro stations.
    3 - Select a metro line and see its metro stations.
    0 - Exit.
    Enter your selection:
  10. On the menu, type 3 and press Enter:
    Metropolitan Area Transit Authority
    ====================================================================
    Metro Lines
    --------------------------------------------------------------------
    1 - Green
    2 - Red
    3 - Yellow
    4 - Blue
    5 - Orange
    6 - Silver
    ====================================================================
    Show the list of metro stations on Line:
  11. On the menu, type 2 and press Enter:
    Metropolitan Area Transit Authority
    ====================================================================
    Metro Stations
    --------------------------------------------------------------------
    Metro Line - Red
    --------------------------------------------------------------------
    1       - 2014 Shady Grove
    2       - 1660 Rockville
    3       - 6497 Twinbrook
    4       - 7385 North Bethesda
    5       - 5739 Grosvenor-Strathmore
    6       - 9795 Medical Center
    7       - 4844 Bethesda
    8       - 7468 Friendship Heights
    9       - 1770 Tenleytown-AU
    10      - 2493 Van Ness-UDC
    11      - 2957 Cleveland Park
    12      - 2969 Woodley Park-Zoo/Adams Morgan
    13      - 5575 Dupont Circle
    14      - 2927 Farragut North
    15      - 4480 Metro Center
    16      - 3584 Gallery Place Chinatown
    17      - 5947 Judiciary Square
    18      - 7720 Union Station
    19      - 5248 NoMa-Gallaudet U
    20      - 1827 Rhode Island Ave-Brentwood
    21      - 3330 Brookland-CUA
    22      - 9794 Fort Totten
    23      - 3860 Takoma
    24      - 1475 Silver Spring
    25      - 7707 Forest Glen
    26      - 6295 Wheaton
    27      - 2837 Glenmont
    ====================================================================
    What do you want to do?
    1 - See a list of metro lines.
    2 - See a list of all metro stations.
    3 - Select a metro line and see its metro stations.
    0 - Exit.
    Enter your selection:
  12. On the menu, type q and press Enter
  13. Type Q to close the window and return to your programming environ
  14. Create a new Console App named PlanarCurves3
  15. To create a new folder, in the Solution Explorer, right-click PlanarCurves3 -> Add -> New Folder
  16. Type Models as the name of the folder
  17. In the Solution Explorer, right-click Models -> Add -> Class...
  18. Change the file Name to Circle
  19. Press Enter
  20. Change the document and the class as follows:
    namespace PlanarCurves3.Models
    {
        internal class Circle
        {
            public const double PI = 3.14;
    
            public double Radius { get; set; }
    
            public Circle()
            {
                Radius = 0.00;
            }
    
            public double CalculateDiameter()
            {
                return Radius * 2.00;
            }
    
            public double CalculateArea()
            {
                return Radius * Radius * PI;
            }
        }
    }
  21. In the Solution Explorer, right-click Program.cs and click Rename
  22. Type Geometry (to get Geometry.cs) and press Enter
  23. Read the message in the message box and click Yes
  24. Click the Geometry.cs tab to access it
  25. Change the document as follows:
    using PlanarCurves3.Models;
    using static System.Console;
    
    var round = new Circle();
    
    WriteLine("=====================================");
    WriteLine("Enter the value to process the circle");
    Write("Radius:      ");
    round.Radius = double.Parse(ReadLine());
    
    WriteLine("=====================================");
    WriteLine("Geometry - Circle Summary");
    WriteLine("-------------------------------------");
    WriteLine("Radius:   {0}", round.Radius);
    WriteLine("Diameter: {0}", round.CalculateDiameter());
    WriteLine("Area:     {0}", round.CalculateArea());
    Write("=====================================");
  26. To execute the application, on the main menu, click Debug -> Start Without Debugging:
  27. When requested, type the Radius as 248.73 and press Enter:
    =====================================
    Enter the value to process the circle
    Radius:      248.73
    =====================================
    Geometry - Circle Summary
    -------------------------------------
    Radius:   248.73
    Diameter: 497.46
    Area:     194261.16450599997
    =====================================
    
    Press any key to close this window . . .
  28. To close the window, press Enter and return to your programming environment
  29. Click the Circle.cs tab to access the class

Only Reading a Value

Introduction

When creating a field of a class, one of the decisions you must make is how the field would get its value(s). To create a field so that objects outside the class can only view its value but cannot change it while the value can be changed inside the class, you must indicate to the the compiler that the value will be treated as read-only.

A Read-Only Tuple

You can create a regular tuple but whose value depends on specific objects. This is the case for a read-only tuple. You can create it in the body of a class and initialize it in a constructor. Here is an example:

public class Memory
{
    public readonly (int numberOfSockets, int memoryInGB) partition;

    public Memory()
    {
        partition = (2, 8);
    }

    public Memory(int capacity)
    {
        partition = (2, 16);
    }
}

A Read-Only Field in a Type

To let you create a read-only field, the C# language provides a keyword named readonly. Therefore, to create a read-only field, declare its variable in the body of the class but outside any method or property. Precede its data type with the readonly keyword. Here is an example:

public class Circle
{
    readonly double PI;
}

You can mark the field with an access level such as private or public, depending on your intentions.

To specify the value of a read-only field, use a constructor, such as the default constructor, to initialize the field. Here is an example:

public class Circle
{
    private double r;

    private readonly double PI;

    public Circle()
    {
       	PI = 3.14;
    }
}

The only difference between a constant variable and a read-only field is that a constant variable must be initialized when creating it. On the other hand, you can create more than one constructor in a class, then assign the same or a different value in each constructor to the read-only field. This means that, because you can initialize a read-only field in a constructor, if you have different constructors, you can also have different values for the same read-only field. Here are examples:

public class Circle
{
    private double r;

    private readonly double PI;

    public Circle()
    {
       	PI = 3.14;
    }

    public Circle(double rad)
    {
       	r = rad;
        PI = 3.14159;
    }

    public double CalculateDiameter()
    {
       	return r * 2;
    }

    public double CalculateArea()
    {
       return r * r * PI;
    }
}

Instead of a constant value, the value of a read-only field can come from an expression. If the value held by a read-only field is gotten from an expression, then the field must be initialized in the(a) constructor with the desired expression.

We know that a constant variable must be initialized when it is created. Although a read-only variable seems to follow the same rule, it doesn't. Remember that you don't need to initialize a read-only variable when you declare it since you can do this in the(a) constructor of the class. Also, because a constructor can be overloaded, a read-only field can hold different values depending on the particular constructor that is accessed at a particular time, but the value of a constant variable cannot change: it is initialized once, in the class (or in a method) and it keeps that value throughout the class (or method).

ApplicationPractical Learning: Creating and Using a Read-Only Field

  1. You can initialize a read-only field in the (a) constructor of its class. For an example, change the Circle class as follows:
    namespace PlanarCurves3.Models
    {
        public class Circle
        {
            public readonly double PI;
    
            public double Radius { get; set; }
    
            public Circle()
            {
                PI = 3.14;
                Radius = 0.00;
            }
    
            public double CalculateDiameter()
            {
                return Radius * 2.00;
            }
    
            public double CalculateArea()
            {
                return Radius * Radius * PI;
            }
        }
    }
  2. Click the Geometry.cs tab
  3. Change the code of the event as follows:
    using PlanarCurves3.Models;
    using static System.Console;
    
    var round = new Circle();
    
    WriteLine("=====================================");
    WriteLine("Enter the value to process the circle");
    Write("Radius:   ");
    round.Radius = double.Parse(ReadLine());
    
    WriteLine("=====================================");
    WriteLine("Geometry - Circle Summary");
    WriteLine("-------------------------------------");
    WriteLine("Radius:   {0}", round.Radius);
    WriteLine("PI:       {0}", round.PI);
    WriteLine("Diameter: {0}", round.CalculateDiameter());
    WriteLine("Area:     {0}", round.CalculateArea());
    Write("=====================================");
  4. To execute the application, on the main menu, click Debug -> Start Without Debugging:
  5. For the Side, type 5377.96 and press Enter:
    =====================================
    Enter the value to process the circle
    Radius:   5377.96
    =====================================
    Geometry - Circle Summary
    -------------------------------------
    Radius:   5377.96
    PI:       3.14
    Diameter: 10755.92
    Area:     90816504.811424
    =====================================
    
    Press any key to close this window . . .
  6. To close the window and return to your programming environment, press K
  7. Click the Circle.cs tab to access the class
  8. Because a read-only field can be initialized in a constructor, each constructor can assign a different value to the field. As a result, a read-only field can have different values. When you create an object, the constructor you choose will provide the value of the read-only field. For examples, change the Circle class as follows:
    namespace PlanarCurves3.Models
    {
        public class Circle
        {
            public readonly double PI;
    
            public double Radius { get; set; }
    
            public Circle()
            {
                PI = 3.14;
                Radius = 0.00;
            }
    
            public Circle(double rad)
            {
                Radius = rad;
                PI = 3.14159;
            }
    
            public double CalculateDiameter()
            {
                return Radius * 2.00;
            }
    
            public double CalculateArea()
            {
                return Radius * Radius * PI;
            }
        }
    }
  9. Click the Geometry.cs tab to access the code
  10. Change the code as follows:
    using PlanarCurves3.Models;
    using static System.Console;
    
    WriteLine("=====================================");
    WriteLine("Enter the value to process the circle");
    Write("Radius:   ");
    double rad = double.Parse(ReadLine());
    
    var round = new Circle(rad);
    
    WriteLine("=====================================");
    WriteLine("Geometry - Circle Summary");
    WriteLine("-------------------------------------");
    WriteLine("Radius:   {0}", round.Radius);
    WriteLine("PI:       {0}", round.PI);
    WriteLine("Diameter: {0}", round.CalculateDiameter());
    WriteLine("Area:     {0}", round.CalculateArea());
    Write("=====================================");
  11. To execute the project, on the main menu, click Debug -> Start Without Debugging
  12. For the Side, type 1327.97
    =====================================
    Enter the value to process the circle
    Radius:   1327.97
    =====================================
    Geometry - Circle Summary
    -------------------------------------
    Radius:   1327.97
    PI:       3.14159
    Diameter: 2655.94
    Area:     5540207.539496231
    =====================================
    
    Press any key to close this window . . .
  13. To close the window and return to your programming environment, press K
  14. Click the Circle.cs tab and change the Circle class as follows:
    namespace PlanarCurves3.Models
    {
        internal class Circle
        {
            public readonly double PI;
    
            public Circle() : this(0.00)
            {
                PI = 3.14;
            }
    
            public Circle(double rad)
            {
                Radius = rad;
                PI = 3.14159;
            }
    
            public double Radius { get; set; }
    
            public double CalculateDiameter() => Radius * 2.00;
    
            public double CalculateArea()     => Radius * Radius * PI;
        }
    }
  15. To execute the project, on the main menu, click Debug -> Start Without Debugging
  16. For the Side, type 1003.77
    =====================================
    Enter the value to process the circle
    Radius:      1003.77
    =====================================
    Geometry - Circle Summary
    -------------------------------------
    Radius:   1003.77
    PI:       3.14159
    Diameter: 2007.54
    Area:     3165322.2397045107
    =====================================
    
    Press any key to close this window . . .
  17. To close the window and return to your programming environment, press L
  18. Start a new Console App named ElectricityDistributionCompany2
  19. To create a new folder, in the Solution Explorer, right-click ElectricityDistributionCompany2 -> Add -> New Folder
  20. Type Models as the name of the folder
  21. In the Solution Edplorer, right-click Models -> Add -> Class...
  22. Change the file Name to Meter
  23. Click Add
  24. Change the class as follows:
    namespace ElectricityDistributionCompany2.Models
    {
        public class Meter
        {
            public string? MeterNumber { get; set; }
            public string? Make { get; set; }
            public string? Model { get; set; }
    
            public string Describe() => Make + " " + Model + " (Mtr #: " + MeterNumber + ")";
        }
    }
  25. In the Solution Edplorer, right-click Models -> Add -> Class...
  26. Change the file Name to CounterReading
  27. Click Add
  28. Change the class as follows:
    public class CounterReading
    {
        private Meter mtr;
        public int TotalUse { get; set; }
    
        public CounterReading()
        {
            mtr = new();
            mtr.Make = "Horriander";
            mtr.Model = "CXL 3600";
            mtr.MeterNumber = "M927084";
        }
    
        public Meter Read() => mtr;
    }
  29. In the Solution Edplorer, right-click Models -> Add -> Class...
  30. Change the file Name to Calculations
  31. Press Enter
  32. Change the class as follows:
    namespace ElectricityDistributionCompany2.Models
    {
        public class Calculations
        {
            public CounterReading Useage { get; set; } = new CounterReading();
    
            public const double CustomerCharge = 7.60;
            public const double DeliveryTaxRate = 6.20;
            public const double EnergyChargeRate = 6.2655;
            public const double GridResilienceChargeRate = 12;
            public const double EnvironmentSurchargeRate = 14.90;
    
            public Calculations() => Useage.TotalUse = 1497;
    
            public double CalculateEnergyCharges() => Useage.TotalUse * EnergyChargeRate / 100;
            public double CalculateGridResilienceCharges() => Useage.TotalUse * GridResilienceChargeRate / 100000;
            public double CalculateDeliveryTaxes() => Useage.TotalUse * DeliveryTaxRate / 10000;
            public double CalculateEnvironmentalSurcharge() => Useage.TotalUse * EnvironmentSurchargeRate / 100000;
    
            public double EvaluateAmountDue()
            {
                return CustomerCharge +
                       CalculateEnergyCharges() +
                       CalculateGridResilienceCharges() +
                       CalculateDeliveryTaxes() +
                       CalculateEnvironmentalSurcharge();
            }
    
            public CounterReading Prepare() => Useage;
        }
    }
  33. In the Solution Edplorer, right-click Models -> Add -> Class...
  34. Change the file Name to ElectriBill
  35. Click Add
  36. Change the class as follows:
    namespace ElectricityDistributionCompany2.Models
    {
        public class ElectriBill
        {
            private Calculations values;
    
            public ElectriBill()
            {
                values = new();
            }
    
            public Calculations Prepare() => values;
    
            public string Summarize()
            {
                return values.Prepare()
                             .Read()
                             .Describe();
            }
        }
    }

A Read-Only Referenced Variable

Remember that, to use a referenced variable, you must assign a previously declared and initialized variable to it. For the same reason, you cannot assign a regular value to a referenced variable. If you do, when you execute the program, the compiler would produce an error. This makes a referenced variable is a read-only item. To re-enforce this idea, you can indicate to the compiler that your referenced variable a read-only item. To do this, follow the ref keyword of the referenced variable with the readonly keyword, as in ref readonly. This can be done as follows:

using static System.Console;

double side = 248.57;
    
ref readonly double oneOf4Sides = ref side;
ref readonly double siding = ref side;
ref readonly double coast = ref side;
    
WriteLine("Square Characteristics");
WriteLine("------------------------");
WriteLine("Original Side:   {0}", side);
WriteLine("Referenced Side: {0}", oneOf4Sides);
WriteLine("Referenced Side: {0}", siding);
WriteLine("Referenced Side: {0}", coast);
WriteLine("========================");

Updating a Referenced Variable

Remember that, when you have declared and initialized a referenced variable, it holds the same value as its referent. As a consequence, if you change the value of the original variable, the value of the referenced variable also changes. This can be illustrated as follows:

using static System.Console;

double side = 248.57;

ref readonly double oneOf4Sides = ref side;
ref readonly double siding = ref side;

WriteLine("Square Characteristics");
WriteLine("------------------------");
WriteLine("Original Side:   {0}", side);
WriteLine("One of 4 Sides:  {0}", oneOf4Sides);
WriteLine("Siding:          {0}", siding);
WriteLine("========================");

side = 66.93;

ref readonly double coast = ref side;
ref readonly double quad = ref side;

WriteLine("Square Characteristics");
WriteLine("------------------------");
WriteLine("Original Side:   {0}", side);
WriteLine("One of 4 Sides:  {0}", oneOf4Sides);
WriteLine("Siding:          {0}", siding);
WriteLine("Coast:           {0}", coast);
WriteLine("Quad Side:       {0}", quad);
WriteLine("========================");

This would produce:

Square Characteristics
------------------------
Original Side:   248.57
One of 4 Sides:  248.57
Siding:          248.57
========================
Square Characteristics
------------------------
Original Side:   66.93
One of 4 Sides:  66.93
Siding:          66.93
Coast:           66.93
Quad Side:       66.93
========================

Press any key to close this window . . .

In the same way, you can change the value of a referent as many times as you want and keep in mind that its associated referenced variable is updated. Therefore, if you are planning to use the value of a referenced variable, make sure it is holding the intended value at that time. As a result, you are free to change the value of the original variable any time but use the referenced variable, knowing that its value will automatically be updated. This can be verified in the following code:

using static System.Console;

WriteLine("Square Characteristics");
WriteLine("------------------------");

double side = 248.57;
ref readonly double oneOf4Sides = ref side;

WriteLine("Original Side:   {0}", side);
WriteLine("Referenced Side: {0}", oneOf4Sides);
WriteLine("------------------------");

side = 937.866;

WriteLine("Original Side:   {0}", side);
WriteLine("Referenced Side: {0}", oneOf4Sides);
WriteLine("------------------------");

side = 66.93;

WriteLine("Original Side:   {0}", side);
WriteLine("Referenced Side: {0}", oneOf4Sides);
WriteLine("------------------------");

side = 1057.48;

WriteLine("Original Side:   {0}", side);
WriteLine("Referenced Side: {0}", oneOf4Sides);
WriteLine("========================");

In the above example, notice that only the value of the referent is updated, but every time, the referenced variable is automatically updated. The above code would produce:

Square Characteristics
------------------------
Original Side:   248.57
Referenced Side: 248.57
------------------------
Original Side:   937.866
Referenced Side: 937.866
------------------------
Original Side:   66.93
Referenced Side: 66.93
------------------------
Original Side:   1057.48
Referenced Side: 1057.48
========================

Press any key to close this window . . .

Passing a Primitive Reference to an Object

Since a referenced variable holds a real value, you can use it wherever you would use the original variable. For example, you can pass it as argument. Here is an example where a referenced variable is passed to a constructor of an object:

using static System.Console;

double side = 248.57;
    
ref double oneOf4Sides = ref side; 
Square sqr = new Square(oneOf4Sides);
    
WriteLine("Square Characteristics");
WriteLine("----------------------------");
WriteLine("Side:      {0}", sqr.Side);
WriteLine("Perimeter: {0}", sqr.CalculatePerimeter());
WriteLine("Area:      {0}", sqr.CalculateArea());
WriteLine("============================");
    
public class Square(double side)
{
    public double Side
    {
        get { return side; }
    }
    
    public double CalculatePerimeter()
    {
        return side * 4;
    }
    
    public double CalculateArea()
    {
        return side * side;
    }
}

When it comes to using a referenced variable as argument, whenever you do that, you must let the compiler know so it would update its operation(s). This can be easily done by re-calling the item(s) that use(s) the argument. Here are examples:

using static System.Console;

// Declare a variable
double side = 248.57;
// Create a referenced variable
ref readonly double oneOf4Sides = ref side;
// Pass the referenced variable to an object
Square sqr = new(oneOf4Sides);

WriteLine("Square Characteristics");
WriteLine("----------------------------");
WriteLine("Side:      {0}", sqr.Side);
WriteLine("Perimeter: {0}", sqr.CalculatePerimeter());
WriteLine("Area:      {0}", sqr.CalculateArea());
WriteLine("============================");

// Change the value of the original variable
side = 937.866;
// Let the compiler know that the value passed to the object has changed
sqr = new(oneOf4Sides);

WriteLine("Square Characteristics");
WriteLine("----------------------------");
WriteLine("Side:      {0}", sqr.Side);
WriteLine("Perimeter: {0}", sqr.CalculatePerimeter());
WriteLine("Area:      {0}", sqr.CalculateArea());
WriteLine("============================");

// Update the original variable
side = 66.93;
// Notify the compiler that the value of the object has changed
sqr = new(oneOf4Sides);

WriteLine("Square Characteristics");
WriteLine("----------------------------");
WriteLine("Side:      {0}", sqr.Side);
WriteLine("Perimeter: {0}", sqr.CalculatePerimeter());
WriteLine("Area:      {0}", sqr.CalculateArea());
WriteLine("============================");

// Update the referent
side = 1057.48;
// Let the compiler know that there is a new value for the object
sqr = new(oneOf4Sides);

WriteLine("Square Characteristics");
WriteLine("----------------------------");
WriteLine("Side:      {0}", sqr.Side);
WriteLine("Perimeter: {0}", sqr.CalculatePerimeter());
WriteLine("Area:      {0}", sqr.CalculateArea());
WriteLine("============================");

public class Square(double side)
{
    public double Side
    {
        get { return side; }
    }

    public double CalculatePerimeter()
    {
        return side * 4;
    }

    public double CalculateArea()
    {
        return side * side;
    }
}

This would produce:

Square Characteristics
----------------------------
Side:      248.57
Perimeter: 994.28
Area:      61787.04489999999
============================
Square Characteristics
----------------------------
Side:      937.866
Perimeter: 3751.464
Area:      879592.633956
============================
Square Characteristics
----------------------------
Side:      66.93
Perimeter: 267.72
Area:      4479.624900000001
============================
Square Characteristics
----------------------------
Side:      1057.48
Perimeter: 4229.92
Area:      1118263.9504
============================

Press any key to close this window . . .

A Read-Only Object Type

We already know that if we create a field that is a class type, we must find a way to initialize the field before it. Such an intialization can be done in a constructor. When studying fields created from primitive types, we saw that, to indicate that the field is initialized in a constructor of the class where the field is created, you can mark that field with the readonly keyword. This feature is also available for fields of class type.

ApplicationPractical Learning: Creating a Read-Only Object

  1. To create a read-only field, click the CounterReading.cs tab and make the following change:
    namespace ElectricityDistributionCompany2.Models
    {
        public class CounterReading
        {
            private readonly Meter mtr;
            public int TotalUse { get; set; }
    
            public CounterReading()
            {
                mtr = new();
                mtr.Make = "Horriander";
                mtr.Model = "CXL 3600";
                mtr.MeterNumber = "M927084";
            }
    
            public Meter Read() => mtr;
        }
    }
  2. To create another read-only field, click the ElectriBill.cs tab and make the following change:
    namespace ElectricityDistributionCompany2.Models
    {
        public class ElectriBill
        {
            private readonly Calculations values;
    
            public ElectriBill()
            {
                values = new();
            }
    
            public Calculations Prepare() => values;
    
            public string Summarize()
            {
                return values.Prepare()
                             .Read()
                             .Describe();
            }
        }
    }
  3. In the Solution Explorer, right-click Program.cs and click Rename
  4. Type BillProcessing (to get BillProcessing.cs) and press Enter
  5. Click the BillProcessing.cs tab to access its document
  6. Change the document as follows:
    using static System.Console;
    using ElectricityDistributionCompany2.Models;
    
    var eb = new ElectriBill();
    
    WriteLine("===================================================================");
    WriteLine("Electricity Distribution Company");
    WriteLine("===================================================================");
    
    WriteLine("Meter #:                     {0}", eb.Prepare()
                                                    .Useage
                                                    .Read()
                                                    .MeterNumber);
    WriteLine("Make:                        {0}", eb.Prepare()
                                                    .Useage
                                                    .Read().Make);
    WriteLine("Model:                       {0}", eb.Prepare()
                                                    .Useage
                                                    .Read().Model);
    WriteLine($"Meter Details:               {eb.Summarize()}");
    WriteLine("-------------------------------------------------------------------");
    WriteLine($"Customer Charge:             {Calculations.CustomerCharge:F}");
    WriteLine($"Delivery Tax Rate:           {Calculations.DeliveryTaxRate:F}");
    WriteLine($"Energy Charge Rate:          {Calculations.EnergyChargeRate:F}");
    WriteLine($"Grid Resilience Charge Rate: {Calculations.GridResilienceChargeRate:F}");
    WriteLine($"Environment Surcharge Rate:  {Calculations.EnvironmentSurchargeRate:F}");
    WriteLine("-------------------------------------------------------------------");
    WriteLine($"Total Use:                   {eb.Prepare().Useage.TotalUse:f}");
    WriteLine($"Environmental Surcharge:     {eb.Prepare().CalculateEnvironmentalSurcharge():f}");
    WriteLine($"Delivery Taxes:              {eb.Prepare().CalculateDeliveryTaxes():f}");
    WriteLine($"Grid Resilience Charges.:    {eb.Prepare().CalculateGridResilienceCharges():f}");
    WriteLine($"Energy Charges.:             {eb.Prepare().CalculateEnergyCharges():f}");
    WriteLine("-------------------------------------------------------------------");
    WriteLine($"Amount Due.:                 {eb.Prepare().EvaluateAmountDue():f}");
    WriteLine("==================================================================="); 
  7. To execute, on the main menu, click Debug -> Start Without Debugging:
    ===================================================================
    Electricity Distribution Company
    ===================================================================
    Meter #:                     M927084
    Make:                        Horriander
    Model:                       CXL 3600
    Meter Details:               Horriander CXL 3600 (Mtr #: M927084)
    -------------------------------------------------------------------
    Customer Charge:             7.60
    Delivery Tax Rate:           6.20
    Energy Charge Rate:          6.27
    Grid Resilience Charge Rate: 12.00
    Environment Surcharge Rate:  14.90
    -------------------------------------------------------------------
    Total Use:                   1497.00
    Environmental Surcharge:     0.22
    Delivery Taxes:              0.93
    Grid Resilience Charges.:    0.18
    Energy Charges.:             93.79
    -------------------------------------------------------------------
    Amount Due.:                 102.73
    ===================================================================
    
    Press any key to close this window . . .
  8. To close the window and return to Microsoft Visual Studio, press Enter

Previous Copyright © 2001-2026, FunctionX Sunday 03 May 2026, 19:58 Next