Home

Introduction to Indexers

 

A Property Can Be Indexed

 

Introduction

In the previous sections, we learned how to create an array, how to assign values to its elements, and how to get the value of each element. Here is an example:

using System;

public class Program
{
    static int Main()
    {
        double[] Numbers = new double[5];

        Numbers[0] = 927.93;
        Numbers[1] = 45.155;
        Numbers[2] = 2.37094;
        Numbers[3] = 73475.25;
        Numbers[4] = 186.72;

        for (int i = 0; i < Numbers.Length; i++)
            Console.WriteLine("Number {0}: {1}", i+1,
			Numbers[i]);

        Console.WriteLine();
        return 0;
    }
}

This would produce:

Number 1: 927,93
Number 2: 45,155
Number 3: 2,37094
Number 4: 73475,25
Number 5: 186,72

Press any key to continue . . .
 

Introduction

In the same way, if we declared an array as a member variable of a class, to access the elements of that member, we had to use an instance of the class, followed by the period operator, followed by the member variable applied with the square brackets. Instead of accessing each element through its member variable, you can create a type of property referred to as an indexer.

Practical Learning: Introducing Indexed Properties

  1. Start a new Console Application named PropertyRental1
  2. To create a new class, on the main menu, click Project -> Add Class...
  3. Set the Name to Property and press Enter
  4. Change the file as follows:
     
    using System;
    
    namespace PropertyRental1
    {
        public enum Condition
        {
            Excellent,
            Good,
            NeedsRepair,
            Unknown
        }
    
        public class Property
        {
            private long propCode;
            private Condition cond;
            private short beds;
            private float baths;
            private decimal val;
    
            public long PropertyCode
            {
                get { return propCode; }
                set { propCode = value; }
            }
    
            public Condition PropertyCondition
            {
                get { return cond; }
                set { cond = value; }
            }
    
            public short Bedrooms
            {
                get { return beds; }
                set { beds = value; }
            }
    
            public float Bathrooms
            {
                get { return (baths <= 0) ? 0.00f : baths; }
                set { baths = value; }
            }
    
            public decimal MonthlyRent
            {
                get { return (val <= 0) ? 0.00M : val; }
                set { val = value; }
            }
    
            public Property()
            {
                Random rnd = new Random();
                propCode = rnd.Next(100000, 999999);
                cond = Condition.Unknown;
                beds = 0;
                baths = 0.0f;
                val = 0.00M;
            }
        }
    }
  5. To create a new class, on the main menu, click Project -> Add Class...
  6. Set the Name to PropertyListing and press Enter
  7. Change the file as follows:
     
    using System;
    
    namespace PropertyRental1
    {
        public class PropertyListing
        {
            public Property[] props;
    
            public PropertyListing()
            {
                Random rnd = new Random();
                prop = new Property[40];
    
                // Create a few properties ready to be rented
                props[0] = new Property();
                props[0].PropertyCode = rnd.Next(100000, 999999);
                props[0].PropertyCondition = Condition.Excellent;
                props[0].Bedrooms = 5;
                props[0].Bathrooms = 3.5f;
                props[0].MonthlyRent = 2650;
    
                props[1] = new Property();
                props[1].PropertyCode = rnd.Next(100000, 999999);
                props[1].PropertyCondition = Condition.Excellent;
                props[1].Bedrooms = 3;
                props[1].Bathrooms = 2.5f;
                props[1].MonthlyRent = 1750;
    
                props[2] = new Property();
                props[2].PropertyCode = rnd.Next(100000, 999999);
                props[2].PropertyCondition = Condition.Good;
                props[2].Bedrooms = 4;
                props[2].Bathrooms = 2.5f;
                props[2].MonthlyRent = 2450;
    
                props[3] = new Property();
                props[3].PropertyCode = rnd.Next(100000, 999999);
                props[3].PropertyCondition = Condition.Excellent;
                props[3].Bedrooms = 1;
                props[3].Bathrooms = 1.0f;
                props[3].MonthlyRent = 880;
    
                props[4] = new Property();
                props[4].PropertyCode = rnd.Next(100000, 999999);
                props[4].PropertyCondition = Condition.Excellent;
                props[4].Bedrooms = 3;
                props[4].Bathrooms = 2.5f;
                props[4].MonthlyRent = 1880;
    
                props[5] = new Property();
                props[5].PropertyCode = rnd.Next(100000, 999999);
                props[5].PropertyCondition = Condition.Good;
                props[5].Bedrooms = 2;
                props[5].Bathrooms = 1.0f;
                props[5].MonthlyRent = 1050;
    
                // Since we don't yet have a complete list of properties
                // Create some empty ones
                for (int i = 6; i < 40; i++)
                {
                    props[i] = new Property();
                }
            }
        }
    }
  8. Access the Program.cs file and change it as follows:
     
    using System;
    
    namespace PropertyRental1
    {
        public class Program
        {
            static int Main()
            {
                PropertyListing properties = new PropertyListing();
                Property prop = new Property();
    
                for (int i = 0; i < 6; i++)
                {
                    Console.WriteLine("{0}.----------------------------------",
    			i + 1);
                    Console.WriteLine("Property #:   {0}",
    				  properties .props[i].PropertyCode);
                    Console.WriteLine("Condition:    {0}",
    				  properties .props[i].PropertyCondition);
                    Console.WriteLine("Bedrooms:     {0}",
    				  properties .props[i].Bedrooms);
                    Console.WriteLine("Bathrooms:    {0}",
    				  properties .props[i].Bathrooms);
                    Console.WriteLine("Market Value: {0}\n",
    			properties .props[i].MonthlyRent.ToString("C"));
                }
                Console.WriteLine("======================================");
    
                return 0;
            }
        }
    }
  9. Press Ctrl + F5 to execute the application. This would produce:
     
    1.----------------------------------
    Property #:   920119
    Condition:    Excellent
    Bedrooms:     5
    Bathrooms:    3.5
    Market Value: $2,650.00
    
    2.----------------------------------
    Property #:   587917
    Condition:    Excellent
    Bedrooms:     3
    Bathrooms:    2.5
    Market Value: $1,750.00
    
    3.----------------------------------
    Property #:   904376
    Condition:    Good
    Bedrooms:     4
    Bathrooms:    2.5
    Market Value: $2,450.00
    
    4.----------------------------------
    Property #:   421662
    Condition:    Excellent
    Bedrooms:     1
    Bathrooms:    1
    Market Value: $880.00
    
    5.----------------------------------
    Property #:   305196
    Condition:    Excellent
    Bedrooms:     3
    Bathrooms:    2.5
    Market Value: $1,880.00
    
    6.----------------------------------
    Property #:   503836
    Condition:    Good
    Bedrooms:     2
    Bathrooms:    1
    Market Value: $1,050.00
    
    ======================================
    Press any key to continue . . .
  10. Close the DOS window

An Indexer

An indexer, also called an indexed property, is a class's property that allows you to access a member variable of a class using the features of an array. To create an indexed property, start the class like any other. In the body of the class, create a field that is an array. Here is an example:

public class Number
{
    double[] Numbers = new double[5];
}

Then, in the body of the class, create a property named this with its accessor(s). The this property must be the same type as the field it will refer to. The property must take a parameter as an array. This means that it must have square brackets. Inside of the brackets, include the parameter you will use as index to access the members of the array.

Traditionally, and as we have seen so far, you usually access the members of an array using an integer-based index. Therefore, you can use an int type as the index of the array. Of course, the index' parameter must have a name, such as i. This would be done as follows:

public class Number
{
    double[] Numbers = new double[5];

    public double this[int i]
    {
    }
}

If you want the property to be read-only, include only a get accessor. In the get accessor, you should return an element of the array field the property refers to, using the parameter of the property. This would be done as follows:

public class Number
{
    double[] Numbers = new double[5];

    public double this[int i]
    {
        get { return Numbers[i]; }
    }
}

Once you have created the indexed property, the class can be used. To start, you can declare a variable of the class. To access its arrayed field, you can apply the square brackets directly to it. Here is an example:

using System;

public class Number
{
    double[] Numbers;

    public double this[int i]
    {
        get { return Numbers[i]; }
    }

    public Number()
    {
        Numbers = new double[5];
        Numbers[0] = 927.93;
        Numbers[1] = 45.155;
        Numbers[2] = 2.37094;
        Numbers[3] = 73475.25;
        Numbers[4] = 186.72;
    }
}

public class Program
{
    static int Main()
    {
        Number nbr = new Number();

        for (int i = 0; i < 5; i++)
            Console.WriteLine("Number {0}: {1}", i + 1, nbr[i]);

        Console.WriteLine();
        return 0;
    }
}

Based on this, a type of formula to create and use a basic indexed property is:

class ClassName
{
    DataType[] ArrayName = new DataType[Index];

    public DataType this[int i]
    {
        get { return ArrayName[i]; }
    }
}

Indexed Properties of Other Primitive Types

In the above example, we created a property that produced double-precision values. When creating an indexed property, you will decide what type of value the property must produce or the type it can have. As opposed to an int or a double, you can also create a property that takes or produces a string. To do this, you can use the above class template with the desired data type, such as string. Here is an example of a string-based indexed property:

using System;

public class Philosopher
{
    string[] phil = new string[8];

    public string this[int i]
    {
        get { return phil[i]; }
    }

    public Philosopher()
    {
        phil[0] = "Aristotle";
        phil[1] = "Emmanuel Kant";
        phil[2] = "Tom Huffman";
        phil[3] = "Judith Jarvis Thompson";
        phil[4] = "Thomas Hobbes";
        phil[5] = "Cornell West";
        phil[6] = "Jane English";
        phil[7] = "James Rachels";
    }
}

public class Program
{
    static int Main()
    {
        Philosopher thinker = new Philosopher();

        for (int i = 0; i < 8; i++)
            Console.WriteLine("Philosopher: {0}", thinker[i]);

        Console.WriteLine();
        return 0;
    }
}

This would produce:

Philosopher: Aristotle
Philosopher: Emmanuel Kant
Philosopher: Tom Huffman
Philosopher: Judith Jarvis Thompson
Philosopher: Thomas Hobbes
Philosopher: Cornell West
Philosopher: Jane English
Philosopher: James Rachels

Press any key to continue . . .

In the same way, you can created a Boolean-based indexed property by simply making it return a bool type. Here is an example:

using System;

public class DrivingWhileIntoxicated
{
    bool[] dwi = new bool[7];

    public bool this[int i]
    {
        get { return dwi[i]; }
    }

    public DrivingWhileIntoxicated()
    {
        dwi[0] = false;
        dwi[1] = true;
        dwi[2] = true;
        dwi[3] = false;
        dwi[5] = false;
        dwi[6] = false;
    }
}

public class Program
{
    static int Main()
    {
        DrivingWhileIntoxicated driving = new DrivingWhileIntoxicated();

        Console.WriteLine("Police Report");
        Console.WriteLine("-------------------------------");
        for(int i = 0; i < 7; i++)
            Console.WriteLine("Driver Was Intoxicated: {0}", driving[i]);

        Console.WriteLine();
        return 0;
    }
}

This would produce:

Police Report
-------------------------------
Driver Was Intoxicated: False
Driver Was Intoxicated: True
Driver Was Intoxicated: True
Driver Was Intoxicated: False
Driver Was Intoxicated: False
Driver Was Intoxicated: False
Driver Was Intoxicated: False

Press any key to continue . . .

Using a Non-Integer-Based Index

In previous lessons, we saw how to create different arrays that are numeric or string based. Here is an example of a float array:

using System;

public class Program
{
    static int Main()
    {
        float[] ages = new float[5];

        ages[0] = 14.50f;
        ages[1] = 12.00f;
        ages[2] = 16.50f;
        ages[3] = 14.00f;
        ages[4] = 15.50f;

        Console.WriteLine("Student Age: {0}", ages[2]);
        Console.WriteLine();
        return 0;
    }
}

When we think of arrays, we usually consider passing an integer-based parameter to the square brackets of the variable, as done for the above ages array:

float[] ages = new float[5];

When using an indexed property, you can use almost any type of index, such as a real value or a string. To do this, in the square brackets of the this property, pass the desired type as the index. Here is an example:

public class StudentAge
{
    public float this[string name]
    {
    }
}

When defining the indexed property, there are two rules you must follow and you are aware of them already because an indexed property is like a method that takes a parameter and doesn't return void. Therefore, when implementing an indexed property, make sure you return the right type of value and make sure you pass the appropriate index to the return value of the this property. Here is an example:

public class StudentAge
{
    public float this[string name]
    {
        get
        {
            if(  name == "Ernestine Jonas" )
                return 14.50f;
            else if( name == "Paul Bertrand Yamaguchi" )
                return 12.50f;
            else if( name == "Helene Jonas" )
                return 16.00f;
            else if( name == "Chrissie Hanson" )
                return 14.00f;
            else if( name == "Bernard Hallo" )
                return 15.50f;
            else
                return 12.00f;
        }
    }
}

Once you have defined the property, you can use it. To access any of its elements, you must pass the appropriate type of index. In this case, the index must be passed as a string and not an integer. You can then do whatever you want with the value produced by the property. For example, you can display it to the user. Here is an example:

using System;

public class StudentAge
{
    public float this[string name]
    {
        get
        {
            if(  name == "Ernestine Jonas" )
                return 14.50f;
            else if( name == "Paul Bertrand Yamaguchi" )
                return 12.50f;
            else if( name == "Helene Jonas" )
                return 16.00f;
            else if( name == "Chrissie Hanson" )
                return 14.00f;
            else if( name == "Bernard Hallo" )
                return 15.50f;
            else
                return 12.00f;
        }
    }
}

public class Program
{
    static int Main()
    {
        StudentAge sa = new StudentAge();
        float age = sa["Paul Bertrand Yamaguchi"];

        Console.WriteLine("Student Name: {0}", age);

        Console.WriteLine();
        return 0;
    }
}

This would produce:

Student Name: 12.5

Press any key to continue . . .

You can also pass an enumeration as an index. To do this, after defining the enumerator, type its name and a parameter name in the square brackets of the this member, then define the property as you see fit. To access the property outside, apply an enumeration member to the square brackets on an instance of the class. Here is an example:

using System;

public enum CategoryFee
{
    Children,
    Adult,
    Senior,
    Unknown
}

public class GolfClubMembership
{
    double[] fee = new double[4];

    public GolfClubMembership()
    {
        fee[0] = 150.95d;
        fee[1] = 250.75d;
        fee[2] = 85.65d;
        fee[3] = 350.00d;
    }

    public double this[CategoryFee cat]
    {
        get
        {
            if (cat == CategoryFee.Children)
                return fee[0];
            else if (cat == CategoryFee.Adult)
                return fee[1];
            else if (cat == CategoryFee.Senior)
                return fee[2];
            else
                return fee[3];
        }
    }
}

public class Program
{
    static int Main()
    {
        GolfClubMembership mbr= new GolfClubMembership();

        Console.WriteLine("Membership Fee: {0}", mbr[CategoryFee.Senior]);

        Console.WriteLine();
        return 0;
    }
}

This would produce:

Membership Fee: 85.65

Press any key to continue . . .

 

 

Practical Learning: Creating an Indexer

  1. To create an indexer, access the PropertyListing.cs file and change it as follows:
     
    using System;
    
    namespace PropertyRental1
    {
        public class PropertyListing
        {
            public Property[] props;
    
            public string this[long code]
            {
                get {
                    for(int i = 0; i < props.Length; i++)
                        if( code == props[i].PropertyCode )
                            return "Property #:   " + props[i].PropertyCode + 
                                   "\nCondition:    " + 
    				props[i].PropertyCondition +
                                   "\nBedrooms:     " + props[i].Bedrooms + 
                                   "\nBathrooms:    " + props[i].Bathrooms +
                                   "\nMonthly Rent: " + 
    				props[i].MonthlyRent.ToString("C");
                    return "Unidentifiable Property";
                }
            }
    
            public PropertyListing()
            {
                . . . No Change
            }
        }
    }
  2. Access the Program.cs file and change it as follows:
     
    using System;
    
    namespace PropertyRental1
    {
        public class Program
        {
            static int Main()
            {
                PropertyListing properties = new PropertyListing();
                long lngCode;
    
                Console.WriteLine("Here is a list of our properties by code");
                for (int i = 0; i < 6; i++)
                    Console.WriteLine("Property Code: {0}",
    			properties.props[i].PropertyCode);
    
                try
                {
                    Console.Write("Enter Property Code: ");
                    lngCode = long.Parse(Console.ReadLine());
    
                    Console.WriteLine("======================================");
                    Console.WriteLine("Property Information");
                    Console.WriteLine("--------------------------------------");
                    Console.WriteLine(properties[lngCode]);
                    Console.WriteLine("======================================");
    
                }
                catch (FormatException)
                {
                    Console.WriteLine("=- Invalid Property Code -=");
                }
    
                return 0;
            }
        }
    }
  3. Press Ctrl + F5 to execute the application. Here is an example:
     
    Here is a list of our properties by code
    Property Code: 355443
    Property Code: 653004
    Property Code: 800118
    Property Code: 839375
    Property Code: 148561
    Property Code: 697001
    Enter Property Code: 697001
    ======================================
    Property Information
    --------------------------------------
    Property #:   697001
    Condition:    Good
    Bedrooms:     2
    Bathrooms:    1
    Monthly Rent: $1,050.00
    ======================================
    Press any key to continue . . .
  4. Close the DOS window
 

Home Copyright © 2007-2012 FunctionX Next