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 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 Volumetrics1
  19. To create a new folder, in the Solution Explorer, right-click Volumetrics1 -> Add -> New Folder
  20. Type Models as the name of the folder
  21. In the Solution Explorer, right-click Models -> Add -> Class...
  22. In the middle list of the Add New Item dialog box, make sure the Class option is selected.
    Change the file Name to Rectangle
  23. Click Add
  24. Start a new Console App named PayrollPreparation4

A Read-Only Array

Introduction

Usually when you declare an array variable in a class (an array as opposed to other types of collections), you may already know the values you want the array to hold, and most of the time, you as the programmer will provide those values as opposed to the user providing them. To assist the compiler, you can create such an array as a read-only object. To do this, apply the readonly keyword to the variable. This can be done as follows:

using static System.Console;

StaffPayroll sp = new();

public class StaffPayroll
{
    // Declaring an array without initializing it
    readonly string[] fullName;

    // Declaring and initializing an array
    readonly double[] week1TimeWorked = new double[5];
    // An array variable of numbers
    readonly double[] week2TimeWorked = new double[5] { 6.00, 8.50, 7.00, 5.50, 6.50 };

    public StaffPayroll()
    {
        // Initializing the array variable
        fullName = new string[3];

        fullName[0] = "Bethanie";
        fullName[1] = "Elizabeth";
        fullName[2] = "Gants";

        WriteLine("Payroll Summary");
        WriteLine("-----------------------------------------------");
        WriteLine("Employee Name:       {0} {1} {2}",
            fullName[0], fullName[1], fullName[2]);

        Prepare();
        Present();
    }

    private void Prepare()
    {
        // Setting the values of the array that was declared and initialized
        week1TimeWorked[0] = 8.00;
        week1TimeWorked[1] = 6.00;
        week1TimeWorked[2] = 9.00;
        week1TimeWorked[3] = 8.50;
        week1TimeWorked[4] = 7.50;
    }

    public void Present()
    {
        WriteLine("===============================================");
        WriteLine("Time Worked");
        WriteLine("-----------------------------------------------");
        WriteLine("Week 1");
        WriteLine("     Monday:         {0:N}", week1TimeWorked[0]);
        WriteLine("     Tuesday:        {0:N}", week1TimeWorked[1]);
        WriteLine("     Wednesday:      {0:N}", week1TimeWorked[2]);
        WriteLine("     Thursday:       {0:N}", week1TimeWorked[3]);
        WriteLine("     Friday:         {0:N}", week1TimeWorked[4]);
        WriteLine("-----------------------------------------------");
        WriteLine("Week 2");
        WriteLine("     Monday:         {0:N}", week2TimeWorked[0]);
        WriteLine("     Tuesday:        {0:N}", week2TimeWorked[1]);
        WriteLine("     Wednesday:      {0:N}", week2TimeWorked[2]);
        WriteLine("     Thursday:       {0:N}", week2TimeWorked[3]);
        WriteLine("     Friday:         {0:N}", week2TimeWorked[4]);
        WriteLine("-----------------------------------------------");
        WriteLine("Total Time Worked:   {0:N}",
                  week1TimeWorked[0] + week1TimeWorked[1] + week1TimeWorked[2] +
                  week1TimeWorked[3] + week1TimeWorked[4] + week2TimeWorked[0] + 
                  week2TimeWorked[1] + week2TimeWorked[2] + week2TimeWorked[3] + 
                  week2TimeWorked[4]);
        WriteLine("===============================================");
    }
}

This would produce:

Payroll Summary
-----------------------------------------------
Employee Name:       Bethanie Elizabeth Gants
===============================================
Time Worked
-----------------------------------------------
Week 1
     Monday:         8.00
     Tuesday:        6.00
     Wednesday:      9.00
     Thursday:       8.50
     Friday:         7.50
-----------------------------------------------
Week 2
     Monday:         6.00
     Tuesday:        8.50
     Wednesday:      7.00
     Thursday:       5.50
     Friday:         6.50
-----------------------------------------------
Total Time Worked:   72.50
===============================================

Press any key to close this window . . .

A Read-Only Referenced Argument

Most of the time, the reason you want to pass an argument by reference is because you want its function to change the value of that argument. In some cases, you may not want the function to change the value of the argument, as is the case for an in argument. If you don't want a function to be able to change the value of a referenced argument, or to inform the compiler that you don't want the function to change the value of a referenced argument, you can pass the argument as read-only. To do this, when creating the function, between the ref keyword and the data type of the parameter, add the readonly keyword. When calling the function, you must pass the argument as a reference, by preceding the argument with the ref keyword. This can be done as follows:

using static System.Console;

void Present(ref readonly double val)
{
    WriteLine("Value: {0}", val);
}

double @double = 397_822.73;

Present(ref @double);

WriteLine("===================================");

This would produce:

Value: 397822.73
===================================

Press any key to close this window . . .

Remember that, if you pass an argument as ref readonly, you are not allowed to change the value of the argument in the body of the function. If you do, the compiler will produce an error.

Practical LearningPractical Learning: Passing Arguments as Read-Only References

  1. Change the Program.cs document as follows:
    using static System.Console;
    
    PreparePayroll();
    
    // -------------------------------------------------------
    
    void IdentifyEmployee(out string fn, out string ln, out double sal)
    {
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Preparation");
        WriteLine("-------------------------------------------------------");
        WriteLine("Enter the following pieces of information");
        WriteLine("-------------------------------------------------------");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
    
        Write("First Name:    ");
        fn = ReadLine()!;
        Write("Last Name:     ");
        ln = ReadLine()!;
        Write("Hourly Salary: ");
        sal = double.Parse(ReadLine()!);
    }
    
    void GetTimeWorked(ref double m, ref double t, ref double w, ref double h, ref double f)
    {
        WriteLine("-------------------------------------------------------");
        WriteLine("Time worked");
        WriteLine("-------------------------------------------------------");
        Write("Monday:        ");
        m = double.Parse(ReadLine()!);
        Write("Tuesday:       ");
        t = double.Parse(ReadLine()!);
        Write("Wednesday:     ");
        w = double.Parse(ReadLine()!);
        Write("Thursday:      ");
        h = double.Parse(ReadLine()!);
        Write("Friday:        ");
        f = double.Parse(ReadLine()!);
    }
    
    double Add2(ref readonly double m, ref readonly double n)
    {
        return m + n;
    }
    
    double Add5(in double a, in double b, in double c, in double d, in double e)
    {
        return a + b + c + d + e;
    }
    
    void EvaluateSalary(ref readonly double time, ref readonly double sal,
                        ref double regTime, ref double regPay, ref double overtime, ref double overPay)
    {
        regTime = time;
        regPay = sal * time;
        overtime = 0.00;
        overPay = 0.00;
    
        if (time is > 40.00)
        {
            regTime = 40.00;
            regPay = sal * 40.00;
            overtime = time - 40.00;
            overPay = sal * 1.50 * overtime;
        }
    }
    
    void PreparePayroll()
    {
        string firstName;
        string lastName;
        double hSalary;
    
        double mon         = 0.00;
        double tue         = 0.00;
        double wed         = 0.00;
        double thu         = 0.00;
        double fri         = 0.00;
    
        double regularTime = 0.00;
        double regularPay  = 0.00;
        double overtime    = 0.00;
        double overtimePay = 0.00;
    
        IdentifyEmployee(out firstName, out lastName, out hSalary);
        GetTimeWorked(ref mon, ref tue, ref wed, ref thu, ref fri);
    
        double timeWorked  = Add5(in mon, in tue, in wed, in thu, in fri);
    
        EvaluateSalary(ref timeWorked, ref hSalary,
                       ref regularTime, ref regularPay, ref overtime, ref overtimePay);
    
        double weeklyPay  = Add2(ref regularPay, ref  overtimePay);
    
        WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
        WriteLine("FUN DEPARTMENT STORE");
        WriteLine("=======================================================");
        WriteLine("Payroll Evaluation");
        WriteLine("=======================================================");
        WriteLine("Employee Information");
        WriteLine("-------------------------------------------------------");
        WriteLine($"Full Name:     {firstName} {lastName}");
        WriteLine($"Hourly Salary: {hSalary:f}");
        WriteLine("=======================================================");
        WriteLine("Time Worked Summary");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday");
        WriteLine("--------+---------+-----------+----------+-------------");
        WriteLine($"  {mon:f}  |   {tue:f}  |    {wed:f}   |   {thu:f}   |  {fri:f}");
        WriteLine("========+=========+===========+==========+=============");
        WriteLine("                                    Pay Summary");
        WriteLine("-------------------------------------------------------");
        WriteLine("                                   Time   Pay");
        WriteLine("-------------------------------------------------------");
        WriteLine($"                     Regular:    {regularTime:f}   {regularPay:f}");
        WriteLine("-------------------------------------------------------");
        WriteLine($"                     Overtime:    {overtime:f}   {overtimePay:f}");
        WriteLine("=======================================================");
        WriteLine($"                     Net Pay:            {weeklyPay:f}");
        WriteLine("=======================================================");
    }
  2. To execute, press Ctrl + F5
  3. Type some values and press Enter after each value:
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Preparation
    -------------------------------------------------------
    Enter the following pieces of information
    -------------------------------------------------------
    Employee Information
    -------------------------------------------------------
    First Name:    Jennifer
    Last Name:     Simms
    Hourly Salary: 31.57
    -------------------------------------------------------
    Time worked
    -------------------------------------------------------
    Monday:        8
    Tuesday:       8
    Wednesday:     8
    Thursday:      8
    Friday:        8
    +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
    FUN DEPARTMENT STORE
    =======================================================
    Payroll Evaluation
    =======================================================
    Employee Information
    -------------------------------------------------------
    Full Name:     Jennifer Simms
    Hourly Salary: 31.57
    =======================================================
    Time Worked Summary
    --------+---------+-----------+----------+-------------
     Monday | Tuesday | Wednesday | Thursday | Friday
    --------+---------+-----------+----------+-------------
      8.00  |   8.00  |    8.00   |   8.00   |  8.00
    ========+=========+===========+==========+=============
                                        Pay Summary
    -------------------------------------------------------
                                       Time   Pay
    -------------------------------------------------------
                         Regular:    40.00   1262.80
    -------------------------------------------------------
                         Overtime:    0.00   0.00
    =======================================================
                         Net Pay:            1262.80
    =======================================================
    
    Press any key to close this window . . .
  4. Press any key to close the window and return to your programming environment
  5. Close Microsoft Visual Studio

A Read-Only Multidimensional Array

When you are creating an array in a class, if you are planning to initialize it in the class, you can (and should) mark the array as read-only. To do this, apply the readonly operator to the variable. This can be done as follows:

using static System.Console;

TriangleInCoordinateSystem tri = new TriangleInCoordinateSystem();

tri.ShowPoints();

Title = "Triangle Coordinates";

WriteLine("====================================");

public record class TriangleInCoordinateSystem
{
    readonly int[,] points;

    public TriangleInCoordinateSystem()
    {
        points = new int[3, 2];

        points[0, 0] = -2; // A(x, )
        points[0, 1] = -3; // A( , y)
        points[1, 0] = 5; // B(x, )
        points[1, 1] = 1; // B( , y)
        points[2, 0] = 4; // C(x, )
        points[2, 1] = -2; // C( , y)
    }

    public void ShowPoints()
    {
        string strCoordinates = "Coordinates of the Triangle" + Environment.NewLine +
                                "A(" + points[0, 0] + ", " + points[0, 1] + ")" + Environment.NewLine +
                                "B(" + points[1, 0] + ", " + points[1, 1] + ")" + Environment.NewLine +
                                "C(" + points[2, 0] + ", " + points[2, 1] + ")";
        WriteLine(strCoordinates);
    }
}

Of course, a null-bound array can be created as read-only:

using static System.Console;

TriangleInCoordinateSystem tri = new TriangleInCoordinateSystem();

tri.ShowPoints();

Title = "Triangle Coordinates";

WriteLine("====================================");

public record class TriangleInCoordinateSystem
{
    private readonly int[,]? points;

    public TriangleInCoordinateSystem()
    {
        points = new int[3, 2];

        points[0, 0] = -2; // A(x, )
        points[0, 1] = -3; // A( , y)
        points[1, 0] = 5; // B(x, )
        points[1, 1] = 1; // B( , y)
        points[2, 0] = 4; // C(x, )
        points[2, 1] = -2; // C( , y)
    }

    public void ShowPoints()
    {
        string strCoordinates = "Coordinates of the Triangle" + Environment.NewLine +
                                "A(" + points?[0, 0] + ", " + points?[0, 1] + ")" + Environment.NewLine +
                                "B(" + points?[1, 0] + ", " + points?1, 1] + ")" + Environment.NewLine +
                                "C(" + points?[2, 0] + ", " + points?[2, 1] + ")";
        WriteLine(strCoordinates);
    }
}

Previous Copyright © 2001-2026, FunctionX Tuesday 25 November 2025, 08:52 Next