Fundamentals of Indexed Properties and Classes

Introduction

Just as an indexed property can take a parameter of a primitive type, you can create an indexer that is of a class type. For example, you can create a class so that one of the its fields declared as an array can be accessed with an index directly applied to an instance of the class.

Practical LearningPractical Learning: Introducing Indexers and Classes

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the middle list of the dialog box, make sure Console App (.NET Framework) is selected.
    Change the Name to PayrollPreparation7
  4. Click OK
  5. On the main menu, right-click PayrollPreparation7 -> Add -> Class...
  6. Type Employee as the name of the class
  7. Press Enter
  8. Change the file as follows:
    namespace PayrollPreparation7
    {
        public class Employee
        {
            public long   EmployeeNumber { get; set; }
            public string FirstName      { get; set; }
            public string LastName       { get; set; }
            public double HourlySalary   { get; set; }
        }
    }
  9. To create a new class, on the main menu, click Project -> Add Class...
  10. Type StaffManagement
  11. Press Enter
  12. Change the file as follows:
    using static System.Console;
    
    namespace PayrollPreparation5
    {
        public class PayrollManagement
        {
            public static int Main(string[] args)
            {
                long emplNbr = 0L;
                StaffManagement staff = new StaffManagement();
    
                WriteLine("     Human Resources - Employees");
                WriteLine("===========================================");
                WriteLine("Empl #     First Name    Last Name  Salary");
                WriteLine("-------------------------------------------");
                for (int i = 0; i < 5; i++)
                    WriteLine(" {0}    {1}   {2}{3}",
                        staff.pers[i].EmployeeNumber, staff.pers[i].FirstName,
                        staff.pers[i].LastName, staff.pers[i].HourlySalary);
                WriteLine("===========================================");
    
                try
                {
                    Write("Enter an employee #: ");
                    emplNbr = long.Parse(ReadLine());
    
                    WriteLine("======================================");
                    WriteLine("Employee Details");
                    WriteLine("--------------------------------------");
                    WriteLine(staff[emplNbr]);
                    WriteLine("======================================");
    
                }
                catch (System.FormatException)
                {
                    WriteLine("=- Invalid Employee Number -=");
                }
    
                return 0;
            }
        }
    }
  13. To create a new class, on the main menu, click Project -> Add Class...
  14. Set the Name to PropertyListing and press Enter
  15. Change the file as follows:
    namespace PayrollPreparation5
    {
        public class StaffManagement
        {
            public Employee[] pers;
    
            public string this[long code]
            {
                get
                {
                    for (int i = 0; i < pers.Length; i++)
                        if (code == pers[i].EmployeeNumber)
                            return "Employee #:    " + pers[i].EmployeeNumber +
                                   "\nFirst Name:    " + pers[i].FirstName +
                                   "\nLast Name:     " + pers[i].LastName +
                                   "\nHourly Salary: " + pers[i].HourlySalary.ToString("F");
                    return "Unidentifiable Employee";
                }
            }
    
            public StaffManagement()
            {
                pers = new Employee[5];
    
                pers[0] = new Employee();
                pers[0].EmployeeNumber = 994_759;
                pers[0].FirstName = "Michael    ";
                pers[0].LastName  = "Grant      ";
                pers[0].HourlySalary = 22.58;
    
                pers[1] = new Employee();
                pers[1].EmployeeNumber = 394_225;
                pers[1].FirstName = "Veronique  ";
                pers[1].LastName  = "Beatten    ";
                pers[1].HourlySalary = 28.07;
    
                pers[2] = new Employee();
                pers[2].EmployeeNumber = 208_249;
                pers[2].FirstName = "George     ";
                pers[2].LastName  = "Kroll      ";
                pers[2].HourlySalary = 17.96;
    
                pers[3] = new Employee();
                pers[3].EmployeeNumber = 592_740;
                pers[3].FirstName = "Maurissette";
                pers[3].LastName  = "Phukan     ";
                pers[3].HourlySalary = 30.05;
    
                pers[4] = new Employee();
                pers[4].EmployeeNumber = 379_725;
                pers[4].FirstName = "Douglas    ";
                pers[4].LastName  = "Sorrel     ";
                pers[4].HourlySalary = 26.37;
            }
        }
    }
  16. In the Solution Explorer, right-click Program.cs and click Rename
  17. Type PayrollPreparation to get PayrollPreparation.cs, and press Enter
  18. In the Solution Explorer, double-click PayrollPreparation.cs to access it and change it as follows:
    using static System.Console;
    
    namespace PayrollPreparation5
    {
        public class PayrollManagement
        {
            public static int Main(string[] args)
            {
                long emplNbr = 0L;
                StaffManagement staff = new StaffManagement();
    
                WriteLine("     Human Resources - Employees");
                WriteLine("===========================================");
                WriteLine("Empl #     First Name    Last Name  Salary");
                WriteLine("-------------------------------------------");
                for (int i = 0; i < 5; i++)
                    WriteLine(" {0}    {1}   {2}{3}",
                        staff.pers[i].EmployeeNumber, staff.pers[i].FirstName,
                        staff.pers[i].LastName, staff.pers[i].HourlySalary);
                WriteLine("===========================================");
    
                try
                {
                    Write("Enter an employee #: ");
                    emplNbr = long.Parse(ReadLine());
    
                    WriteLine("======================================");
                    WriteLine("Employee Details");
                    WriteLine("--------------------------------------");
                    WriteLine(staff[emplNbr]);
                    WriteLine("======================================");
    
                }
                catch (System.FormatException)
                {
                    WriteLine("=- Invalid Employee Number -=");
                }
    
                return 0;
            }
        }
    }
  19. Press Ctrl + F5 to execute the application. Here is an example:
         Human Resources - Employees
    ===========================================
    Empl #     First Name    Last Name  Salary
    -------------------------------------------
     994759    Michael       Grant      22.58
     394225    Veronique     Beatten    28.07
     208249    George        Kroll      17.96
     592740    Maurissette   Phukan     30.05
     379725    Douglas       Sorrel     26.37
    ===========================================
    Enter an employee #:
  20. At the prompt, type 994759 and press Enter
  21.      Human Resources - Employees
    ===========================================
    Empl #     First Name    Last Name  Salary
    -------------------------------------------
     994759    Michael       Grant      22.58
     394225    Veronique     Beatten    28.07
     208249    George        Kroll      17.96
     592740    Maurissette   Phukan     30.05
     379725    Douglas       Sorrel     26.37
    ===========================================
    Enter an employee #: 994759
    ======================================
    Employee Details
    --------------------------------------
    Employee #:    994759
    First Name:    Michael
    Last Name:     Grant
    Hourly Salary: 22.58
    ======================================
    Press any key to continue . . .
  22. Press Enter to close the DOS window and return to your programming environment

An Integral Class-Based Indexed Property

Before designing an indexer that is class-based, first create the class that will be used as the data type. The class can be simple or complex as you judge it necessary. Here is an example of a simple class:

public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Gender { get; set; }
}

When creating the class that will host the indexed property, declare an array field for the class. Then, create the this property with the desired accessor(s). Here is an example:

public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Gender { get; set; }
}

public class SchoolRegistration
{
    Student[] std = new Student[5];

    public Student this[int i]
    {
        get { return std[i]; }
    }
}

After creating the indexing class, you can use it and access the indexer. For example, you can retrieve its value(s). Here is an example:

using System;

public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int    Gender { get; set; }
}

public class SchoolRegistration
{
    Student[] std = new Student[5];

    public Student this[int i]
    {
        get { return std[i]; }
    }

    public SchoolRegistration()
    {
        std[0] = new Student();
        std[0].FirstName = "Alfredo";
        std[0].LastName = "Olmos";
        std[0].Gender = 2;

        std[1] = new Student();
        std[1].FirstName = "Patricia";
        std[1].LastName = "Katts";
        std[1].Gender = 1;

        std[2] = new Student();
        std[2].FirstName = "Josiane";
        std[2].LastName = "Euler";
        std[2].Gender = 1;

        std[3] = new Student();
        std[3].FirstName = "Joan";
        std[3].LastName = "Jones";
        std[3].Gender = 3;

        std[4] = new Student();
        std[4].FirstName = "George";
        std[4].LastName = "Paulson";
        std[4].Gender = 2;
    }
}

public class Exercise
{
    static int Main(string[] args)
    {
        var pupils = new SchoolRegistration();

        for (var i = 0; i < 5; i++)
        {
	    Student pupil = pupils[i];

            Console.WriteLine("Student Information");
            Console.WriteLine("---------------------");
            Console.WriteLine("First Name: {0}", pupil.FirstName);
            Console.WriteLine("Last Name:  {0}", pupil.LastName);
            Console.WriteLine("Gender:     {0}\n",
                             (pupil.Gender == 1 ? "Female" :
                             (pupil.Gender == 2 ? "Male" : "Unknown")));
        }

        return 0;
    }
}

This would produce:

Student Information
---------------------
First Name: Alfredo
Last Name:  Olmos
Gender:     Male

Student Information
---------------------
First Name: Patricia
Last Name:  Katts
Gender:     Female

Student Information
---------------------
First Name: Josiane
Last Name:  Euler
Gender:     Female

Student Information
---------------------
First Name: Joan
Last Name:  Jones
Gender:     Unknown

Student Information
---------------------
First Name: George
Last Name:  Paulson
Gender:     Male

Press any key to continue . . .

Practical LearningPractical Learning: Using an Integer-Based Indexer

  1. To create an indexer that takes an integer and returns an object, access the StaffMenagement.cs file and change it as follows:
    namespace PayrollPreparation5
    {
        public class StaffManagement
        {
            public Employee[] pers;
    
            public Employee this[int i]
            {
                get
                {
                    return pers[i];
                }
            }
    
            public StaffManagement()
            {
                pers = new Employee[5];
    
                pers[0] = new Employee();
                pers[0].EmployeeNumber = 994_759;
                pers[0].FirstName = "Michael    ";
                pers[0].LastName  = "Grant      ";
                pers[0].HourlySalary = 22.58;
    
                pers[1] = new Employee();
                pers[1].EmployeeNumber = 394_225;
                pers[1].FirstName = "Veronique  ";
                pers[1].LastName  = "Beatten    ";
                pers[1].HourlySalary = 28.07;
    
                pers[2] = new Employee();
                pers[2].EmployeeNumber = 208_249;
                pers[2].FirstName = "George     ";
                pers[2].LastName  = "Kroll      ";
                pers[2].HourlySalary = 17.96;
    
                pers[3] = new Employee();
                pers[3].EmployeeNumber = 592_740;
                pers[3].FirstName = "Maurissette";
                pers[3].LastName  = "Phukan     ";
                pers[3].HourlySalary = 30.05;
    
                pers[4] = new Employee();
                pers[4].EmployeeNumber = 379_725;
                pers[4].FirstName = "Douglas    ";
                pers[4].LastName  = "Sorrel     ";
                pers[4].HourlySalary = 26.37;
            }
        }
    }
  2. Access the PayrollPreparation.cs document and change it as follows:
    using static System.Console;
    
    namespace PayrollPreparation5
    {
        public class PayrollManagement
        {
            public static int Main(string[] args)
            {
                StaffManagement staff = new StaffManagement();
    
                WriteLine("     Human Resources - Employees");
                WriteLine("===========================================");
                WriteLine("Empl #     First Name    Last Name  Salary");
                WriteLine("-------------------------------------------");
                for (int i = 0; i < 5; i++)
                {
                    Employee clerk = staff[i];
    
                    WriteLine(" {0}    {1}   {2}{3}",
                        clerk.EmployeeNumber, clerk.FirstName,
                        clerk.LastName, clerk.HourlySalary);
                }
                    
                WriteLine("===========================================");
    
                return 0;
            }
        }
    }
  3. Press Ctrl + F5 to execute the application
         Human Resources - Employees
    ===========================================
    Empl #     First Name    Last Name  Salary
    -------------------------------------------
     994759    Michael       Grant      22.58
     394225    Veronique     Beatten    28.07
     208249    George        Kroll      17.96
     592740    Maurissette   Phukan     30.05
     379725    Douglas       Sorrel     26.37
    ===========================================
    Press any key to continue . . .
  4. Press Enter to close the DOS window and return to your programming environment
  5. Access the Employee.cs document and change it as follows:
    namespace PayrollPreparation5
    {
        public class Employee
        {
            public long   EmployeeNumber { get; set; }
            public string FirstName      { get; set; }
            public string LastName       { get; set; }
            public double HourlySalary   { get; set; }
    
            public override string ToString()
            {
                return $"Employee #:    {EmployeeNumber}\n" +
                       $"First Name:    {FirstName}\n" +
                       $"Last Name:     {LastName}\n" +
                       $"Hourly Salary: {HourlySalary}";
            }
        }
    }

An Indexed Property Using Another Primitive Type

As done for primitive types, an indexer can take a parameter other than an integer. In some cases, you may use your class or a class created by someone else and need to access an element of the array without information other than its index. Consider the following program:

public enum Classification
{
    Female,
    Male,
    Unknown
}

public class Student
{
    public long StudentID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Classification Gender;

    public override string ToString()
    {
        string str = "Student ID: " + StudentID +
                     "\nFirst Name: " + firstName +
                     "\nLast Name:  " + lastName +
                     "\nGender:     " + Gender;
        return str;
    }
}

public class SchoolRegistration
{
    Student[] std = new Student[50];

    public Student this[...]
    {
    }
}

Previously, we saw that you could create an indexer that takes a type than an integer. For example, we saw that a string could be used as an index.

By now, we know that a basic indexed property produces (or all the indexed properties we have studied so far produce) only one value. If you have a class that has only one field or property, this would be enough. In reality, most of the time, a class has many fields and/or properties. In such a case, when you create an indexer , you need to be able to refer to one exact element of the array. To make this possible, you must define a way to point to the particular element you want. One way you can do this is to use one field of the class as a reference. This is better if that field holds unique values among the other elements of the array. For our Student class, we could use the StudentID field (because we will make sure that each student has a unique ID). You can start the property as follows:

public class SchoolRegistration
{
    Student[] std = new Student[5];

    public Student this[long id]
    {
    }
}

When a user uses this property, he or she must provide a value that uniquely identifies an element of the array. You in turn, when you get this value, you can search for it in the array. If you find it and the array has a get accessor, you can then return the desired but appropriate value. Here is how this can be done:

public class SchoolRegistration
{
    Student[] students = new Student[50];

    public Student this[long id]
    {
        get
        {
            for (int i = 0; i < students.Length; i++)
            {
                if (students[i].StudentID == id)
                    return students[i];
            }
            // Unknown student or the number was not found
            return null;
        }
    }
}

After creating the indexer, you can use it. Once again, you must follow the rules of a method that takes an argument and returns a value other than void. In this case, the indexer must take a string and it must return a Student object. Here is an example:

using System;

public enum Classification
{
    Female,
    Male,
    Unknown
}

public class Student
{
    public long   StudentID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Classification Gender { get; set; }

    public override string ToString()
    {
        string str = "Student ID: " + StudentID +
                     "\nFirst Name: " + FirstName +
                     "\nLast Name:  " + LastName +
                     "\nGender:     " + Gender;
        return str;
    }
}

public class SchoolRegistration
{
    Student[] students = new Student[50];

    public Student this[long id]
    {
        get
        {
            for (int i = 0; i < students.Length; i++)
            {
                if (students[i].StudentID == id)
                    return students[i];
            }
            // Unknown student or the number was not found
            return null;
        }
    }

    public SchoolRegistration()
    {
        students[0] = new Student();
        students[0].StudentID = 917294;
        students[0].FirstName = "Gabrielle";
        students[0].LastName = "Mukoko";
        students[0].Gender = Classification.Female;

        students[1] = new Student();
        students[1].StudentID = 283764;
        students[1].FirstName = "Patrick";
        students[1].LastName = "Katts";
        students[1].Gender = Classification.Unknown;

        students[2] = new Student();
        students[2].StudentID = 192046;
        students[2].FirstName = "Armand";
        students[2].LastName = "Essono";
        students[2].Gender = Classification.Male;

        students[3] = new Student();
        students[3].StudentID = 618268;
        students[3].FirstName = "Bertrand";
        students[3].LastName = "Wenger";
        students[3].Gender = Classification.Male;

        students[4] = new Student();
        students[4].StudentID = 820648;
        students[4].FirstName = "Hortense";
        students[4].LastName = "McNeal";
        students[4].Gender = Classification.Female;
    }
}

public class Exercise
{
    static int Main(string[] args)
    {
        var pupils = new SchoolRegistration();
        var pupil = pupils[820648];

        Console.WriteLine("Student Information");
        Console.WriteLine("---------------------");
        Console.WriteLine("First Name: {0}", pupil.FirstName);
        Console.WriteLine("Last Name:  {0}", pupil.LastName);
        Console.WriteLine("Gender:     {0}\n", pupil.Gender);

        pupil = pupils[192046];

        Console.WriteLine("Student Information");
        Console.WriteLine("---------------------");
        Console.WriteLine("First Name: {0}", pupil.FirstName);
        Console.WriteLine("Last Name:  {0}", pupil.LastName);
        Console.WriteLine("Gender:     {0}\n", pupil.Gender);

        return 0;
    }
}

This would produce:

Student Information
---------------------
First Name: Hortense
Last Name:  McNeal
Gender:     Female

Student Information
---------------------
First Name: Armand
Last Name:  Essono
Gender:     Male

Press any key to continue . . .

Topics on Indexed Properties and Classes

A Class as Index

As opposed to returning a class, an indexer can use a class as its index. When creating such a property, the primary action you must take is to include a class and its name as a parameter to the this property. You can start such a class as follows:

using System;

public enum Classification
{
    Female,
    Male,
    Unknown
}

public class Student
{
    public long           StudentID { get; set; }
    public string         FirstName { get; set; }
    public string         LastName  { get; set; }
    public Classification Gender    { get; set; }
}

public class SchoolRegistration
{
    public string this[Student std]
    {
    }
}

When implementing the class, you should proceed the same way we have done so far following the rules of a method that takes an argument and returns a value other than void. Here is an example:

public class SchoolRegistration
{
    Student[] students = new Student[50];

    public string this[Student std]
    {
        get
        {
            for (int i = 0; i < students.Length; i++)
            {
                if (std.StudentID == students[i].StudentID)

                    return "Student ID: " + students[i].StudentID +
                           "\nFirst Name: " + students[i].FirstName +
                           "\nLast Name:  " + students[i].LastName +
                           "\nGender:     " + students[i].Gender;
            }

            // Unknown student or the number was not found
            return "";
        }
    }
}

After creating the property, you can use it. To do this, you must pass an object that is the type of the index. You can then use the returned value as you see fit. Here is an example:

using System;

public enum Classification
{
    Female,
    Male,
    Unknown
}

public class Student
{
    public long           StudentID { get; set; }
    public string         FirstName { get; set; }
    public string         LastName  { get; set; }
    public Classification Gender    { get; set; }
}

public class SchoolRegistration
{
    Student[] students = new Student[50];

    public string this[Student std]
    {
        get
        {
            for (int i = 0; i < students.Length; i++)
            {
                if (std.StudentID == students[i].StudentID)

                    return "Student ID: " + students[i].StudentID +
                           "\nFirst Name: " + students[i].FirstName +
                           "\nLast Name:  " + students[i].LastName +
                           "\nGender:     " + students[i].Gender;
            }

            // Unknown student or the number was not found
            return "";
        }
    }

    public SchoolRegistration()
    {
        students[0] = new Student();
        students[0].StudentID = 917294;
        students[0].FirstName = "Gabrielle";
        students[0].LastName = "Mukoko";
        students[0].Gender = Classification.Female;

        students[1] = new Student();
        students[1].StudentID = 283764;
        students[1].FirstName = "Patrick";
        students[1].LastName = "Katts";
        students[1].Gender = Classification.Unknown;

        students[2] = new Student();
        students[2].StudentID = 192046;
        students[2].FirstName = "Armand";
        students[2].LastName = "Essono";
        students[2].Gender = Classification.Male;

        students[3] = new Student();
        students[3].StudentID = 618268;
        students[3].FirstName = "Bertrand";
        students[3].LastName = "Wenger";
        students[3].Gender = Classification.Male;

        students[4] = new Student();
        students[4].StudentID = 820648;
        students[4].FirstName = "Hortense";
        students[4].LastName = "McNeal";
        students[4].Gender = Classification.Female;

        students[5] = new Student();
        students[5].StudentID  = 917394;
        students[5].FirstName = "Alfredo";
        students[5].LastName = "Olmos";
        students[5].Gender = Classification.Unknown;

        students[6] = new Student();
        students[6].StudentID  = 163864;
        students[6].FirstName = "Josiane";
        students[6].LastName = "Euler";
        students[6].Gender = Classification.Female;

        students[7] = new Student();
        students[7].StudentID  = 826384;
        students[7].FirstName = "Joan";
        students[7].LastName = "Jones";
        students[7].Gender =  Classification.Female ;
    }
}

public class Exercise
{
    static int Main(string[] args)
    {
        var pupils = new SchoolRegistration();

        var pupil = new Student();
        pupil.StudentID = 820648;

        var strStudent = pupils[pupil];
        Console.WriteLine("=====================");
        Console.WriteLine("Student Information");
        Console.WriteLine("---------------------");
        Console.WriteLine(strStudent);

        //pupil = new Student();
        pupil.StudentID = 192046;
        strStudent = pupils[pupil];

        Console.WriteLine("=====================");
        Console.WriteLine("Student Information");
        Console.WriteLine("---------------------");
        Console.WriteLine(strStudent);

        Console.WriteLine("=====================\n");
        return 0;
    }
}

This would produce:

=====================
Student Information
---------------------
Student ID: 820648
First Name: Hortense
Last Name:  McNeal
Gender:     Female
=====================
Student Information
---------------------
Student ID: 192046
First Name: Armand
Last Name:  Essono
Gender:     Male
=====================

Press any key to continue . . .

You can also directly pass an instance of the class in the square brackets of the object that holds the indexed property, as long as you specify the object. Here is an example:

using System;

public enum Classification
{
    Female,
    Male,
    Unknown
}

public class Student
{
    public long           StudentID { get; set; }
    public string         FirstName { get; set; }
    public string         LastName  { get; set; }
    public Classification Gender    { get; set; }

    public Student()
    {
    }

    public Student(long id)
    {
        this.StudentID = id;
    }
}

public class SchoolRegistration
{
    Student[] students = new Student[50];

    public string this[Student std]
    {
        . . . No Change
    }

    public SchoolRegistration()
    {
        . . . No Change
    }
}

public class Exercise
{
    static int Main(string[] args)
    {
        var pupils = new SchoolRegistration();

        var strStudent = pupils[new Student(618268)];

        Console.WriteLine("=====================");
        Console.WriteLine("Student Information");
        Console.WriteLine("---------------------");
        Console.WriteLine(strStudent);

        Console.WriteLine("=====================\n");
        return 0;
    }
}

This would produce:

=====================
Student Information
---------------------
Student ID: 618268
First Name: Bertrand
Last Name:  Wenger
Gender:     Male
=====================

Press any key to continue . . .

Overloading a Class-Based Indexed Property

As mentioned for indexers that return primitive types, you can overload an indexed property that produces a class. You do this following the same rules applied to method overloading and arrays:

Practical LearningPractical Learning: Overloading an Indexer

  1. To overload the indexer, access the StaffManagement.cs file and change it as follows:
    namespace PayrollPreparation5
    {
        public class StaffManagement
        {
            public Employee[] pers;
    
            public Employee this[int i]
            {
                get
                {
                    if((i >= 0) && (i < pers.Length))
                        return pers[i];
                    throw null;
                }
            }
    
            public Employee this[long nbr]
            {
                get
                {
                    for(int i = 0; i < pers.Length; i++)
                        if (nbr == pers[i].EmployeeNumber)
                            return pers[i];
                    return null;
                }
            }
    
            public StaffManagement()
            {
                pers = new Employee[5];
    
                pers[0] = new Employee();
                pers[0].EmployeeNumber = 994_759;
                pers[0].FirstName = "Michael    ";
                pers[0].LastName  = "Grant      ";
                pers[0].HourlySalary = 22.58;
    
                pers[1] = new Employee();
                pers[1].EmployeeNumber = 394_225;
                pers[1].FirstName = "Veronique  ";
                pers[1].LastName  = "Beatten    ";
                pers[1].HourlySalary = 28.07;
    
                pers[2] = new Employee();
                pers[2].EmployeeNumber = 208_249;
                pers[2].FirstName = "George     ";
                pers[2].LastName  = "Kroll      ";
                pers[2].HourlySalary = 17.96;
    
                pers[3] = new Employee();
                pers[3].EmployeeNumber = 592_740;
                pers[3].FirstName = "Maurissette";
                pers[3].LastName  = "Phukan     ";
                pers[3].HourlySalary = 30.05;
    
                pers[4] = new Employee();
                pers[4].EmployeeNumber = 379_725;
                pers[4].FirstName = "Douglas    ";
                pers[4].LastName  = "Sorrel     ";
                pers[4].HourlySalary = 26.37;
            }
        }
    }
  2. Access the PayrollPreparation.cs document and change it as follows:
    using static System.Console;
    
    namespace PayrollPreparation5
    {
        public class PayrollManagement
        {
            public static int Main(string[] args)
            {
                long emplNbr = 0L;
                StaffManagement staff = new StaffManagement();
    
                WriteLine("     Human Resources - Employees");
                WriteLine("===========================================");
                WriteLine("Empl #     First Name    Last Name  Salary");
                WriteLine("-------------------------------------------");
                for (int i = 0; i < 5; i++)
                {
                    Employee clerk = staff[i];
    
                    WriteLine(" {0}    {1}   {2}{3}",
                        clerk.EmployeeNumber, clerk.FirstName,
                        clerk.LastName, clerk.HourlySalary);
                }
                    
                WriteLine("===========================================");
    
                try
                {
                    Write("Enter an employee #: ");
                    emplNbr = long.Parse(ReadLine());
    
                    WriteLine("======================================");
                    WriteLine("Employee Details");
                    WriteLine("--------------------------------------");
                    WriteLine(staff[emplNbr]);
                    WriteLine("======================================");
    
                }
                catch (System.FormatException)
                {
                    WriteLine("=- Invalid Employee Number -=");
                }
    
                return 0;
            }
        }
    }
  3. Press Ctrl + F5 to execute the application
  4. When prompted, type 208249 and press Enter:
         Human Resources - Employees
    ===========================================
    Empl #     First Name    Last Name  Salary
    -------------------------------------------
     994759    Michael       Grant      22.58
     394225    Veronique     Beatten    28.07
     208249    George        Kroll      17.96
     592740    Maurissette   Phukan     30.05
     379725    Douglas       Sorrel     26.37
    ===========================================
    Enter an employee #: 208249
    ======================================
    Employee Details
    --------------------------------------
    Employee #:    208249
    First Name:    George
    Last Name:     Kroll
    Hourly Salary: 17.96
    ======================================
    Press any key to continue . . .
  5. Press Enter to close the DOS window and return to your programming environment

Read/Write Indexed Properties

As done for a primitive type, you can allow the clients of your indexer to assign values to the array's elements. Once again, when defining the property, you should include a set accessor to it. In the set accessor, you should assign the value keyword to an element of the array. Here is an example:

public class SchoolRegistration
{
    Student[] std = new Student[5];

    public Student this[int i]
    {
        get { return std[i]; }
        set { std[i] = value; }
    }
}

After doing this, you can create an element of the array by applying the square brackets to the instance of the class and assigning the desired value to it. The problem with the class is that, since it may have many fields (or properties), to completely define each element, you must provide a value to the member variables of the class itself. Here is an example:

using System;

public enum Classification
{
    Female,
    Male,
    Unknown
}

public class Student
{
    public long           StudentID { get; set; }
    public string         FirstName { get; set; }
    public string         LastName  { get; set; }
    public Classification Gender    { get; set; }

    public override string ToString()
    {
        string str = "Student ID: " + StudentID +
                     "\nFirst Name: " + FirstName +
                     "\nLast Name:  " + LastName +
                     "\nGender:     " + Gender;
        return str;
    }
}

public class SchoolRegistration
{
    Student[] std = new Student[5];

    public Student this[int i]
    {
        get { return std[i]; }
        set { std[i] = value; }
    }
}

public class Exercise
{
    static int Main(string[] args)
    {
        var registration = new SchoolRegistration();

        var stud = new Student();
        stud.StudentID = 604057;
        stud.FirstName = "Gertrude";
        stud.LastName = "Monayong";
        stud.Gender = Classification.Female;
        registration[2] = stud;

        Console.WriteLine("Student Information");
        Console.WriteLine("---------------------");
        Console.WriteLine("First Name: {0}", registration[2].FirstName);
        Console.WriteLine("Last Name:  {0}", registration[2].LastName);
        Console.WriteLine("Gender:     {0}\n",registration[2].Gender);
         
        return 0;
    }
}

This would produce:

Student Information
---------------------
First Name: Gertrude
Last Name:  Monayong
Gender:     Female

Press any key to continue . . .

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2008-2019, FunctionX Next