Other Types of Properties

Static Properties

When creating a class, if you want to access one of its properties without using an instance of the class, you can crea the property as static. You create the property like any other, except that 1) you must apply the static keyword, 2) you must access the property directly from the name of the class. Here is an example:

using static System.Console;

namespace BusinessManagement
{
    public class Contractor
    {
        private int nbr;
        private string nm;
        private double sal;

        private static string auth;

        public int Code
        {
            get { return nbr; }
            set { nbr = value; }
        }

        public string FullName
        {
            get { return nm; }
            set { nm = value; }
        }
        public double HourlySalary
        {
            get { return sal; }
            set { sal = value; }
        }

        public static string Status
        {
            get
            {
                return auth;
            }
            set
            {
                auth = value;
            }
        }

        public Contractor(int nbr, string name, double wage)
        {
            Code = nbr;
            FullName = name;
            HourlySalary = wage;
        }
    }

    public class Exercise
    {
        public static void Present(Contractor worker)
        {
            WriteLine("Apartments Rental Management");
            WriteLine("=============================");
            WriteLine("Contract Work");
            WriteLine("Work Status: {0,13}", Contractor.Status);
            WriteLine("-----------------------------");
            WriteLine("Contractor Code: {0,8}", worker.Code);
            WriteLine("Full Name: {0,18}", worker.FullName);
            WriteLine("Pay Rate: {0,12}", worker.HourlySalary);
            WriteLine("=============================");
        }

        static int Main()
        {
            Contractor seasonal = new Contractor(80_270_485, "Joshua Eulaw", 28.17D);

            Contractor.Status = "Full Time";

            Present(seasonal);

            return 0;
        }
    }
}

This would produce:

Apartments Rental Management
=============================
Contract Work
Work Status:     Full Time
-----------------------------
Contractor Code: 80270485
Full Name:       Joshua Eulaw
Pay Rate:        28.17
=============================
Press any key to continue . . .

Remember that a static member doesn't use an instance of a class. This means that you can access it whether an object of the class is first created or not. Consider the following example:

using static System.Console;

namespace BusinessManagement
{
    public class Contractor
    {
        private int nbr;
        private string nm;
        private double sal;

        private static string auth;

        public int Code
        {
            get { return nbr; }
            set { nbr = value; }
        }

        public string FullName
        {
            get { return nm; }
            set { nm = value; }
        }
        public double HourlySalary
        {
            get { return sal; }
            set { sal = value; }
        }

        public static string Status
        {
            get { return auth; }
            set { auth = value; }
        }

        public Contractor(int nbr, string name, double wage)
        {
            Code = nbr;
            FullName = name;
            HourlySalary = wage;
        }
    }

    public class Exercise
    {
        public static void Present(Contractor worker)
        {
            WriteLine("Apartments Rental Management");
            WriteLine("=============================");
            WriteLine("Contract Work");
            WriteLine("Work Status: {0,13}", Contractor.Status);
            WriteLine("-----------------------------");
            WriteLine("Contractor Code: {0,8}", worker.Code);
            WriteLine("Full Name: {0,18}", worker.FullName);
            WriteLine("Pay Rate: {0,12}", worker.HourlySalary);
            WriteLine("=============================");
        }

        static int Main()
        {
            Contractor.Status = "Full Time";

            Present(new Contractor(80_270_485, "Joshua Eulaw", 28.17D));

            return 0;
        }
    }
}

Remember that a static class is a class whose all members are static. If you create a static class, every property you add to it must be static.

Boolean Properties

A Boolean property is one that deals with true and false values. When creating the property, set its data type as bool. If you decide to use a get section, make it return a Boolean value. If you want to use a set section, you can assign value to a private field you would have created. Other than that, you can use a Boolean property by following the logic we have seen so far. Here is an example of creating and using a Boolean property:

using static System.Console;

namespace ApartmentRentalManagement
{
    public class Apartment
    {
        private string nbr;
        private int beds;
        private bool can;

        public string UnitNumber
        {
            get { return nbr;  }
            set { nbr = value; }
        }

        public int Bedrooms
        {
            get { return beds; }
            set { beds = value; }
        }
        public bool Available
        {
            get { return can;  }
            set { can = value; }
        }
    }

    public class Exercise
    {
        static int Main()
        {
            Apartment unit = new Apartment();

            unit.UnitNumber = "#D8";
            unit.Bedrooms = 1;
            unit.Available = true;

            WriteLine("Apartment Rental Management");
            WriteLine("===========================");
            WriteLine("Apartment #: {0,5}", unit.UnitNumber);
            WriteLine("Bedrooms: {0,6}", unit.Bedrooms);
            WriteLine("Available: {0,8}", unit.Available);
            WriteLine("===========================");

            return 0;
        }
    }
}

Properties and Enumerations

You can create a property that uses an enumeration as its type, a property can be created from it. To create a property of an enumeration type, use the same steps as for a primitive data type. Of course, you first need an enumeration. You can first create a private field that will serve as a relay. You can then follow the same steps we revied to create a read-only property, a write-only property, or a read-write property. Here is an example:

public enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }

public class RealEstate
{
    PropertyType pt;

    public RealEstate(PropertyType category)
    {
        pt = category;
    }

    public PropertyType Type
    {
        get
        {
            return pt;
        }
        set
        {
            pt = value;
        }
    }
}

Before using the property, you can first declare a variable of the class, then access the property from that variable. You can then display the value of the property. Here is an example of creating and using an enumerated property:

using static System.Console;

namespace BusinessManagement
{
    public enum Availability
    {
        Available = 1,
        Occupied  = 2,
    }

    public class Apartment
    {
        private string nbr;
        private int beds;
        private Availability useage;

        public string UnitNumber
        {
            get { return nbr;  }
            set { nbr = value; }
        }

        public int Bedrooms
        {
            get { return beds;  }
            set { beds = value; }
        }

        public Availability Status
        {
            get { return useage;  }
            set { useage = value; }
        }
    }

    public class Exercise
    {
        static int Main()
        {
            Apartment unit = new Apartment();

            unit.UnitNumber = "#D8";
            unit.Bedrooms = 1;
            unit.Status = Availability.Available;

            WriteLine("Apartment Rental Management");
            WriteLine("===========================");
            WriteLine("Apartment #: {0,5}", unit.UnitNumber);
            WriteLine("Bedrooms: {0,6}", unit.Bedrooms);
            WriteLine("Available: {0,8}", unit.Status);
            WriteLine("------------------------------");

            unit.UnitNumber = "#B2";
            unit.Bedrooms = 3;
            unit.Status = Availability.Occupied;

            WriteLine("Apartment #: {0,5}", unit.UnitNumber);
            WriteLine("Bedrooms: {0,6}", unit.Bedrooms);
            WriteLine("Available: {0,8}", unit.Status);
            WriteLine("===========================");

            return 0;
        }
    }
}

Keep in mind that the property is of the type of an enumeration. This means that you cannot request its value like that of a primitive type and, when manipulating it, you must process it appropriately.

If the property doesn't need to process anything or to valid the values passed to it, you can make create it as an automatic property. Here is an example:

public enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }

public class RealEstate
{
    public RealEstate(PropertyType type)
    {
        Category = type;
    }

    public PropertyType Category { get; set; }
}

Of course, you can create an enumeration-based property that is static. Here are two examples:

public enum Alignment
{
    FarLeft, Left, CenterLeft,
    Center,
    CenterRight, Right, FarRight
}

public class PoliticalParty
{
    private static Alignment align;

    static public Alignment Affiliation
    {
        get
        {
            return align;
        }

        set
        {
            align = value;
        }
    }

    public static Alignment Policy { get; set; }
}

A Class as a Property

After creating a class, it becomes a data type in its own right. As a normal data type, the value of a class can be validated (evaluated, rejected, or retrieved). Based on these characteristics of a class, you can create a property from it.

To create a property that is based on a class, primarily follow the same formulas we have applied to the other properties. The most important aspect to remember is that the class is composite. That is, it is (likely) made of members (properties and/or fields) of various types.

Practical LearningPractical Learning: Creating a Class-Based Property

  1. Click the LoanContract.cs tab and change the class as follows:
    namespace WattsALoan1
    {
        public class LoanContract
        {
            private int    nbr;
            private string fn;
            private string ln;
            private double principal;
            private double rate;
            private int    per;
    
            private Employee empl;
    
            internal int AccountNumber
            {
                get
                {
                    return this.nbr; // The "this" object is optional
                }
    
                set
                {
                    this.nbr = value; // The "this" object is optional
                }
            }
    
            internal string CustomerFirstName
            {
                get
                {
                    return this.fn;
                }
    
                set
                {
                    this.fn = value;
                }
            }
    
            internal string CustomerLastName
            {
                get
                {
                    return ln;
                }
    
                set
                {
                    ln = value;
                }
            }
    
            internal double LoanAmount
            {
                get
                {
                    return principal;
                }
    
                set
                {
                    principal = value;
                }
            }
    
            internal double InterestRate
            {
                get
                {
                    return rate;
                }
    
                set
                {
                    rate = value;
                }
            }
    
            internal int Periods
            {
                get
                {
                    return per;
                }
    
                set
                {
                    per = value;
                }
            }
            internal double InterestAmount
            {
                get
                {
                    return principal * (rate / 100D) * (per / 12);
                }
            }
            internal double FutureValue
            {
                get
                {
                    return principal + InterestAmount;
                }
            }
            internal double MonthlyPayment
            {
                get
                {
                    return FutureValue / per;
                }
            }
    
            internal Employee Clerk
            {
                get { return empl;  }
                set { empl = value; }
            }
        }
    }
  2. Click the WattsAloan.cs tab and change the document as follows:
    using static System.Console;
    
    namespace WattsALoan1
    {
        public class WattsALoan
        {
            private static void Present(LoanContract summary)
            {
                WriteLine("Watts' A Loan");
                WriteLine("============================================================");
                WriteLine("Loan Application");
                WriteLine("------------------------------------------------------------");
                WriteLine("Account Processed by: {0}", summary.Clerk.Identification);
                WriteLine("============================================================");
                WriteLine("Account Details");
                WriteLine("Account #: {0}", summary.AccountNumber);
                WriteLine("Customer Name: {0} {1}", summary.CustomerFirstName,
                            summary.CustomerLastName);
                WriteLine("Loan Amount: {0:C}", summary.LoanAmount);
                WriteLine("Interest Rate: {0:P}", summary.InterestRate / 100);
                WriteLine("Periods: {0} Months", summary.Periods);
                WriteLine("Interest Amount: {0:C}", summary.InterestAmount);
                WriteLine("Future Value: {0:C}", summary.FutureValue);
                WriteLine("Regular Payment: {0:C}/Month", summary.MonthlyPayment);
                WriteLine("============================================================");
            }
    
            private static Employee IdentifyClerk()
            {
                Employee staff = new Employee();
    
                WriteLine("Watts' A Loan");
                WriteLine("============================================================");
                WriteLine("Employee Identification");
                WriteLine("------------------------------------------------------------");
                Write("Enter Employee #: ");
                staff.EmployeeNumber = int.Parse(ReadLine());
                Write("Employee First Name: ");
                staff.FirstName = ReadLine();
                Write("Employee Last Name: ");
                staff.LastName = ReadLine();
                Write("Employment Title: ");
                staff.Title = ReadLine();
    
                return staff;
            }
    
            private static LoanContract Prepare()
            {
                int nbr = 0, months = 0;
                double amount = 0D, rate = 0D;
                string first = null, last = null;
                Employee staff = null;
    
                staff = IdentifyClerk();
    
                WriteLine("Watts' A Loan");
                WriteLine("============================================================");
                WriteLine("Loan Application");
                WriteLine("------------------------------------------------------------");
                Write("Enter Account #: ");
                nbr = int.Parse(ReadLine());
                Write("Customer First Name: ");
                first = ReadLine();
                Write("Customer Last Name: ");
                last = ReadLine();
                Write("Amount of Loan: ");
                amount = double.Parse(ReadLine());
                Write("Interest Rate: ");
                rate = double.Parse(ReadLine());
                Write("Number of Months: ");
                months = int.Parse(ReadLine());
    
                LoanContract contract = new LoanContract(nbr, first, last, amount, rate, months);
                contract.Clerk = staff;
    
                return contract;
            }
    
            static void Main()
            {
                LoanContract contract = Prepare();
    
                Clear();
    
                Present(contract);
            }
        }
    }
  3. To execute, on the main menu, clic Debug and click Start Without Debugging
  4. Enter the values as follows:
    Watts' A Loan
    ============================================================
    Employee Identification
    ------------------------------------------------------------
    Enter Employee #: 429374
    Employee First Name: Denise
    Employee Last Name: Leighton
    Employment Title: Accounts Manager
    Watts' A Loan
    ============================================================
    Loan Application
    ------------------------------------------------------------
    Enter Account #: 708692
    Customer First Name: Joanne
    Customer Last Name: Kennan
    Amount of Loan: 2500
    Interest Rate: 14.65
    Number of Months: 36
    The final results are:
    Watts' A Loan
    ============================================================
    Loan Application
    ------------------------------------------------------------
    Account Processed by: 429374 - Denise Leighton (Accounts Manager)
    ============================================================
    Account Details
    Account #: 708692
    Customer Name: Joanne Kennan
    Loan Amount: $2,500.00
    Interest Rate: 14.65%
    Periods: 36 Months
    Interest Amount: $1,098.75
    Future Value: $3,598.75
    Regular Payment: $99.97/Month
    ============================================================
    Press any key to continue . . .
  5. Press Enter to close the DOS window

Automatic Properties

Introduction to Automatic Properties

Most of the properties we have created so far didn't process any data, they simply represented a piece of information each. You can create such a property with simple code.

Practical LearningPractical Learning: Introducing Automatic Properties

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New -> Project...
  3. In the middle list, click Console App(.NET Framework)
  4. Change the Name to WattsALoan2
  5. Click OK
  6. To create a new class, on the main menu, click Project -> Add -> Class...
  7. Type Employee
  8. Click Add

Introduction to Automatic Read-Only Properties

To create a read-only property that simply provides its value to other members of the same class or to clients of the class, in the body of the property, include only the get; expression. Here is an example:

class Square
{
    public string Side
    {
        get;
    }
}

To use such a property, you must find a way to first specify its value. Probably the most common way to do this is to create a constructor that takes an argument for the property. Then, in the body of the constructor, assign the argument to the property. You can then use the property to get its value. Here is an example:

using static System.Console;

namespace Geometry
{
    public class Square
    {
        public Square(double side)
        {
            Side = side;
        }

        public double Side
        {
            get;
        }

        public double Perimeter
        {
            get { return Side * 4; }
        }
    }

    public class Exercise
    {
        static int Main()
        {
            Square plate = new Square(48.36);

            WriteLine("Square Characteristics");
            WriteLine("===========================");
            WriteLine("Side: {0,10}", plate.Side);
            WriteLine("Perimeter: {0}", plate.Perimeter);
            WriteLine("===========================");

            return 0;
        }
    }
}

This would produce:

Square Characteristics
===========================
Side:      48.36
Perimeter: 193.44
===========================
Press any key to continue . . .

Initializing a Read-Only Automatic Property

To provide the initial value of an automatic property, you have various options. The classic way is to provide the value in a constructor of the class. Here is an example:

using static System.Console;

namespace BusinessManagement
{
    public class Square
    {
        public Square()
        {
            Side = 68.79;
        }

        public double Side
        {
            get;
        }

        public double Perimeter
        {
            get { return Side * 4; }
        }
    }

    public class Exercise
    {
        static int Main()
        {
            Square plate = new Square();

            WriteLine("Square Characteristics");
            WriteLine("===========================");
            WriteLine("Side: {0,10}", plate.Side);
            WriteLine("Perimeter: {0}", plate.Perimeter);
            WriteLine("===========================");

            return 0;
        }
    }
}

This would produce:

Square Characteristics
===========================
Side:      68.79
Perimeter: 275.16
===========================
Press any key to continue . . .

As an alternative, create the property without a body. Then assign a value to it using the => operator. You can assign a constant value. Here are two examples:

using static System.Console;

namespace Geometry
{
    public class Triangle
    {
        public double Base => 317.97;
        public double Height => 159.36;

        public double Area
        {
            get { return Base * Height / 2; }
        }
    }

    public class Exercise
    {
        static int Main()
        {
            Triangle side3 = new Triangle();

            WriteLine("Triangle Characteristics");
            WriteLine("===========================");
            WriteLine("Base:   {0,2}", side3.Base);
            WriteLine("Height: {0}", side3.Height);
            WriteLine("Area:   {0,3}", side3.Area);
            WriteLine("===========================");

            return 0;
        }
    }
}

You can use this technique to specify the expression of a read-only property. Here are two examples:

using static System.Console;

namespace Geometry
{
    public class Square
    {
        public Square(double side)
        {
            Side = side;
        }
        public double Side { get; }

        public double Perimeter => Side * 4;
        public double Area => Side * Side;
    }

    public class Exercise
    {
        static int Main()
        {
            Square plate = new Square(442.86);

            WriteLine("Square Characteristics");
            WriteLine("===========================");
            WriteLine("Side: {0,11}", plate.Side);
            WriteLine("Perimeter: {0}", plate.Perimeter);
            WriteLine("Area: {0,16}", plate.Area);
            WriteLine("===========================");

            return 0;
        }
    }
}

If you decide to use this technique to specify the expression of a property, the expresion must be simple and not include any conditional statement(s).

Introduction to Automatic Read-Write Properties

A simple but complete property is one that doesn't process any data. To create such a property, in its body, simply provide the get; set; expression. Here is an example:

public class Square
{
    public double Side
    {
        get;
        set;
    }
}

When using an object of the class, to specify a value, you can assign the value to the property. On the other hand, you can get the value of the property.

Practical LearningPractical Learning: Creating Automatic Properties

  1. Change the Employee class as follows:
    namespace WattsALoan2
    {
        public class Employee
        {
            public int EmployeeNumber { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Title { get; set; }
    
            public string Identification
            {
                get
                {
                    return EmployeeNumber + " - " + FirstName + " " + LastName + " (" + Title + ")";
                }
            }
        }
    }
  2. To create a new class, in the Solution Explorer, right-click WattsALoan2 -> Add -> Class...
  3. Type LoanContract
  4. Click Add
  5. Change the class as follows:
    namespace WattsALoan2
    {
        public class LoanContract
        {
            internal int      AccountNumber     { get; set; }
            internal string   CustomerFirstName { get; set; }
            internal string   CustomerLastName  { get; set; }
            internal double   LoanAmount        { get; set; }
            internal double   InterestRate      { get; set; }
            internal int      Periods           { get; set; }
            internal Employee Clerk             { get; set; }
    
            internal double InterestAmount => LoanAmount * (InterestRate / 100D) * (Periods / 12);
            internal double FutureValue    => LoanAmount + InterestAmount;
            internal double MonthlyPayment => FutureValue / Periods;
        }
    }
  6. In the Solution Explorer, right-click Program.cs and click Rename
  7. Type WattsALoan to get WattsALoan.cs and press Enter
  8. Click Yes on the message box
  9. Change the WattsALoan class as follows:
    using static System.Console;
    
    namespace WattsALoan1
    {
        public class WattsALoan
        {
            private static void Present(LoanContract summary)
            {
                WriteLine("Watts' A Loan");
                WriteLine("============================================================");
                WriteLine("Loan Application");
                WriteLine("------------------------------------------------------------");
                WriteLine("Account Processed by: {0}", summary.Clerk.Identification);
                WriteLine("============================================================");
                WriteLine("Account Details");
                WriteLine("Account #: {0}", summary.AccountNumber);
                WriteLine("Customer Name: {0} {1}", summary.CustomerFirstName,
                            summary.CustomerLastName);
                WriteLine("Loan Amount: {0:C}", summary.LoanAmount);
                WriteLine("Interest Rate: {0:P}", summary.InterestRate / 100);
                WriteLine("Periods: {0} Months", summary.Periods);
                WriteLine("Interest Amount: {0:C}", summary.InterestAmount);
                WriteLine("Future Value: {0:C}", summary.FutureValue);
                WriteLine("Regular Payment: {0:C}/Month", summary.MonthlyPayment);
                WriteLine("============================================================");
            }
    
            private static Employee IdentifyClerk()
            {
                Employee staff = new Employee();
    
                WriteLine("Watts' A Loan");
                WriteLine("============================================================");
                WriteLine("Employee Identification");
                WriteLine("------------------------------------------------------------");
                Write("Enter Employee #: ");
                staff.EmployeeNumber = int.Parse(ReadLine());
                Write("Employee First Name: ");
                staff.FirstName = ReadLine();
                Write("Employee Last Name: ");
                staff.LastName = ReadLine();
                Write("Employment Title: ");
                staff.Title = ReadLine();
    
                return staff;
            }
    
            private static LoanContract Prepare()
            {
                LoanContract contract = new LoanContract();
    
                contract.Clerk = IdentifyClerk();
                
                WriteLine("============================================================");
                WriteLine("Loan Application");
                WriteLine("------------------------------------------------------------");
                Write("Enter Account #: ");
                contract.AccountNumber = int.Parse(ReadLine());
                Write("Customer First Name: ");
                contract.CustomerFirstName = ReadLine();
                Write("Customer Last Name: ");
                contract.CustomerLastName = ReadLine();
                Write("Amount of Loan: ");
                contract.LoanAmount = double.Parse(ReadLine());
                Write("Interest Rate: ");
                contract.InterestRate = double.Parse(ReadLine());
                Write("Number of Months: ");
                contract.Periods = int.Parse(ReadLine());
    
                return contract;
            }
    
            static void Main()
            {
                LoanContract contract = Prepare();
    
                Clear();
    
                Present(contract);
            }
        }
    }
  10. To execute, on the main menu, clic Debug and click Start Without Debugging
  11. Enter the values as follows:
    Watts' A Loan
    ============================================================
    Employee Identification
    ------------------------------------------------------------
    Enter Employee #: 836486
    Employee First Name: Thomas
    Employee Last Name: Felton
    Employment Title: Accounts Representative
    ============================================================
    Loan Application
    ------------------------------------------------------------
    Enter Account #: 937942
    Customer First Name: Gerard
    Customer Last Name: Maloney
    Amount of Loan: 22748
    Interest Rate: 10.25
    Number of Months: 60
    The final results are:
    Watts' A Loan
    ============================================================
    Loan Application
    ------------------------------------------------------------
    Account Processed by: 836486 - Thomas Felton (Accounts Representative)
    ============================================================
    Account Details
    Account #: 937942
    Customer Name: Gerard Maloney
    Loan Amount: $22,748.00
    Interest Rate: 10.25%
    Periods: 60 Months
    Interest Amount: $11,658.35
    Future Value: $34,406.35
    Regular Payment: $573.44/Month
    ============================================================
    Press any key to continue . . .
  12. Press Enter to close the DOS window

Initializing an Automatic Read/Write Property

To provide the intial value of a property, you have various options. As we saw for the read-only property, you can assign a value in a constructor of the class.

using static System.Math;
using static System.Console;

namespace Geometry
{
    public class Circle
    {
        public Circle(double rad)
        {
            Radius = 228.77;
        }
        public double Radius { get; set; }

        public double Diameter => Radius * 2;
        public double Area => Radius * Radius * PI;
    }

    public class Exercise
    {
        static int Main()
        {
            Circle round = new Circle(442.86);

            WriteLine("Circle Characteristics");
            WriteLine("===========================");
            WriteLine("Radius: {0,8}", round.Radius);
            WriteLine("Diameter: {0}", round.Diameter);
            WriteLine("Area: {0,20}", round.Area);
            WriteLine("===========================");

            return 0;
        }
    }
}

This would produce:

Circle Characteristics
===========================
Radius:   228.77
Diameter: 457.54
Area:     164417.491167025
===========================
Press any key to continue . . .

As an alternative, outside the body of the automatic property, assign the desired value. Here is an example:

using static System.Math;
using static System.Console;

namespace Geometry
{
    public class Circle
    {
        public double Radius { get; set; } = 228.77;

        public double Diameter => Radius * 2;
        public double Area => Radius * Radius * PI;
    }

    public class Exercise
    {
        static int Main()
        {
            Circle round = new Circle();

            WriteLine("Circle Characteristics");
            WriteLine("===========================");
            WriteLine("Radius: {0,8}", round.Radius);
            WriteLine("Diameter: {0}", round.Diameter);
            WriteLine("Area: {0,20}", round.Area);
            WriteLine("===========================");

            return 0;
        }
    }
}

Practical LearningPractical Learning: Initializing an Automatic Read/Write Property

  1. To start a new application, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the middle list, click Empty Project
  3. Change the Name to Chemistry5 and press Enter
  4. To create a new file, on the main menu, click Project -> Add Class...
  5. In the middle list, mahe sure Class is selected.
    Change the Name of the file to Element
  6. Click Add
  7. Complete the Customer.cs file as follows:
    namespace Chemistry01
    {
        public enum Phase
        {
            Gas,
            Liquid,
            Solid,
            Unknown
        }
    
        public class Element
        {
            public string Symbol       { get; set; } = "H";
            public string ElementName  { get; set; } = "Hydrogen";
            public int    AtomicNumber { get; set; } = 1;
            public double AtomicWeight { get; set; } = 1.008;
            public Phase  Phase        { get; set; } = Phase.Gas;
    
            public Element()
            {
            }
    
            public Element(int number)
            {
                AtomicNumber = number;
            }
    
            public Element(string symbol)
            {
                Symbol = symbol;
            }
    
            public Element(int number, string symbol, string name, double mass, Phase phase)
            {
                ElementName  = name;
                AtomicWeight = mass;
                Phase        = phase;
                AtomicNumber = number;
                Symbol       = symbol;
            }
        }
    }
  8. To create a new file, in the Solution Explorer, right-click Chemistry5 -> Add -> Class...
  9. In the middle list, make sure Class is selected.
    Change the Name to Chemistry
  10. Press Enter
  11. Change the class as follows:
    using static System.Console;
    
    namespace Chemistry01
    {
        public class Chemistry
        {
            private static void Describe(Element e)
            {
                WriteLine("Chemistry - " + e.ElementName);
                WriteLine("------------------------");
                WriteLine("Symbol:        " + e.Symbol);
                WriteLine("Element Name:  " + e.ElementName);
                WriteLine("Atomic Number: " + e.AtomicNumber);
                WriteLine("Atomic Weight: " + e.AtomicWeight);
                WriteLine("Phase:         " + e.Phase);
            }
    
            public static int Main()
            {
                Element elm = null;
    
                Element H = new Element(1, "H", "Hydrogen", 1.008, Phase.Gas);
                Element He = new Element(2, "He", "Helium", 4.002602, Phase.Gas);
                Element Li = new Element(3, "Li", "Lithium", 6.94, Phase.Solid);
                Element Be = new Element(4, "Be", "Beryllium", 9.0121831, Phase.Solid);
                Element B = new Element(5, "B", "Boron", 10.81, Phase.Solid);
                Element C = new Element(number: 6, symbol: "C", name: "Carbon", mass: 12.011, phase: Phase.Solid);
                Element N = new Element(7, "N", "Nitrogen", 14.007, Phase.Gas);
                Element O = new Element(8, "O", "Oxygen", 15.999, Phase.Gas);
                Element F = new Element(9, "F", "Fluorine", 15.999, Phase.Gas);
                Element Ne = new Element("Ne") { AtomicNumber = 10, ElementName = "Neon", AtomicWeight = 20.1797, Phase = Phase.Gas };
                Element Na = new Element(11, "Na", "Sodium", 22.98976928, Phase.Solid);
                Element Mg = new Element(12, "Mg", "Magnesium", 24.305, Phase.Solid);
                Element Al = new Element(13, "Al", "Aluminium", 26.9815385, Phase.Solid);
                Element Si = new Element() { ElementName = "Silicon", AtomicWeight = 28.085, Symbol = "Si", AtomicNumber = 14, Phase = Phase.Solid };
                Element P = new Element() { ElementName = "Phosphorus", AtomicWeight = 30.973761998, Symbol = "P", AtomicNumber = 15, Phase = Phase.Solid };
                Element S = new Element(16, "S", "Sulfur", 32.06, Phase.Solid);
                Element Cl = new Element(17, "Cl", "Chlorine", 35.45, Phase.Gas);
                Element Ar = new Element(18, "Ar", "Argon", 39.792, Phase.Gas);
    
                WriteLine("Chemistry - Periodic Table");
                WriteLine("------------------------------------------------");
                Write("Type the chemical symbol of an element you want to review (from H to Ar): ");
                string answer = ReadLine();
    
                Clear();
    
                switch (answer)
                {
                    case "ar":
                    case "Ar":
                    case "aR":
                    case "AR":
                        elm = Ar;
                        break;
                    case "Al":
                    case "AL":
                    case "aL":
                    case "al":
                        elm = Al;
                        break;
                    case "b":
                    case "B":
                        elm = B;
                        break;
                    case "be":
                    case "Be":
                    case "bE":
                    case "BE":
                        elm = Be;
                        break;
                    case "C":
                    case "c":
                        elm = C;
                        break;
                    case "cl":
                    case "Cl":
                    case "cL":
                    case "CL":
                        elm = Cl;
                        break;
                    default:
                        WriteLine("You must type a valid chemical element symbol.");
                        break;
                    case "F":
                    case "f":
                        elm = F;
                        break;
                    case "h":
                    case "H":
                        elm = H;
                        break;
                    case "he":
                    case "HE":
                    case "He":
                    case "hE":
                        elm = He;
                        break;
                    case "li":
                    case "Li":
                    case "LI":
                    case "lI":
                        elm = Li;
                        break;
                    case "MG":
                    case "mG":
                    case "Mg":
                    case "mg":
                        elm = Mg;
                        break;
                    case "N":
                    case "n":
                        elm = N;
                        break;
                    case "Na":
                    case "na":
                    case "NA":
                    case "nA":
                        elm = Na;
                        break;
                    case "NE":
                    case "ne":
                    case "Ne":
                    case "nE":
                        elm = Ne;
                        break;
                    case "o":
                    case "O":
                        elm = O;
                        break;
                    case "p":
                    case "P":
                        elm = P;
                        break;
                    case "S":
                    case "s":
                        elm = S;
                        break;
                    case "SI":
                    case "Si":
                    case "sI":
                    case "si":
                        elm = Si;
                        break;
                }
    
                Describe(elm);
                WriteLine("================================================");
    
                return 0;
            }
        }
    }
  12. To execute, on the main menu, click Debug -> Start Without Debugging:
    Chemistry - Periodic Table
    ------------------------------------------------
    Type the chemical symbol of an element you want to review (from H to Ar):
  13. When prompted, type ar
    Chemistry - Periodic Table
    ------------------------------------------------
    Type the chemical symbol of an element you want to review (from H to Cl): ar
  14. Press Enter:
    Chemistry - Argon
    ------------------------
    Symbol:        Ar
    Element Name:  Argon
    Atomic Number: 18
    Atomic Weight: 39.792
    Phase:         Gas
    ================================================
    Press any key to continue . . .
  15. Press Enter to close the window and return to your programming environment

Fundamental Built-In Enumerations

Introductory to Built-In Enumerations

The .NET Framework uses various enumerations in all of its sub-libraries. To use an enumeration, you must know the library in which the enumeration is defined.

The Built-In Color Enumeration

To help you use colors in your applications, the .NET Framework provides an enumeration named Color. It is defined in the System.Drawing namespace. All of its members are easily recognizable names of colors such as Black, White, Red, Blue, Blue, Yellow, etc.

The Environment Class

Introduction

The .NET Framework provides a static class named Environment. This class quickly and easily gives some information about the application that is currently running and some objects you can use in your application. The Environment class is defined in the System namespace. This means that you don't have to do anything to access it, since it is automatically available whenever you create a C# application.

Creating a New Line

When we were introduced to the Console class, we saw that, one way to create a new line was to call the Console.WriteLine() method, and this feature is not available for the Console.Write() method. The Environment class provides another solution. To let you add a new line, the Environment class is equipped with a property named NewLine. To use it, add it to a string,, which can be done using the + operator. Here are examples:

using static System.Console;

public class VaccinationCampaign
{
    public static voidMain()
    {
        WriteLine("Department of Health");
        WriteLine("=============================");
        WriteLine("Patient's Diagnosis");
        WriteLine("-----------------------------");
        Write("Patient Name: Jerome Abondo" + System.Environment.NewLine);
        Write("Gender:       Male" + System.Environment.NewLine);
        Write("Age Range:    Adult" + System.Environment.NewLine);
        WriteLine("=============================");
    }
}

This would produce:

Department of Health
=============================
Patient's Diagnosis
-----------------------------
Patient Name: Jerome Abondo
Gender:       Male
Age Range:    Adult
=============================
Press any key to continue . . .

As mentioned earlier, Environment is a static class. This means that, to use it, you can first type using static System.Environment; in the top section of your file. After that, you can simply type the name of the class member you want to use. Here is an example:

using static System.Console;
using static System.Environment;

public class VaccinationCampaign
{
    public static int Main()
    {
        WriteLine("Department of Health");
        WriteLine("=============================");
        WriteLine("Patient's Diagnosis");
        WriteLine("-----------------------------");
        Write("Patient Name: Jerome Abondo" + NewLine);
        Write("Gender:       Male" + NewLine);
        Write("Age Range:    Adult" + NewLine);
        WriteLine("=============================");

        return 0;
    }
}

Getting the Machine Name

It used to be difficult to know the name of the computer on which your application is running. To let you easily get this information, the Environment class provides a property named MachineName. Here is an example:

class Exercise
{
    static void Main()
    {
        System.Console.WriteLine("Machine Name: {0}", System.Environment.MachineName);
    }
}

Get the Operation System's Version

To assist you with knowing the version of the operating system on which the application is running, the Environment class provides the OSVersion property. Here is an example:

class Exercise
{
    static void Main()
    {
        System.Console.WriteLine("Operating System on Current Machine: {0}", System.Environment.OSVersion);
    }
}

Getting the Current User's name

At any time, if you want to know the user name of the person who is currently using your application, you can get the value of the UserName property of the Environment class.

The Microsoft Windows operation system is usually installed on the C: drive with most of its drivers in a folder named System32 that is located either under Windows or WinNT. This full path of the driver's main folder is referred to as the system directory.

Getting the System Directory

To assist you with finding out the path to the system directory, the Environment class is equipped with a property named SystemDirectory.

ApplicationPractical Learning: Ending the Lesson


Previous Copyright © 2001-2019, FunctionX Next