Introduction to Indexed Properties

Introduction

We already know 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:

<!DOCTYPE html>
<html>
<head>
<title>Numbers</title>
</head>
<body>
<h1>Numbers</h1>

@{
    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++)
{
    <p>Number @(i + 1): @numbers[i]</p>
}
</body>
</html>

This would produce:

String Comparison

In the same way, if you create an array as a field of a class, to access an element of that member, you can 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 LearningPractical Learning: Introducing Indexed Properties

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the New Project dialog box, in the middle frame, make sure ASP.NET Web Application (.NET Framework) is selected.
    Change the project Name to CountriesStatistics09
  4. Click OK
  5. In the New ASP.NET Web Application dialog box, in the templates list, click the MVC icon.
    Click OK
  6. In the Solution Explorer, expand Controllers and double-click HomeController.cs to open it
  7. Add two methods as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MetroSystem11.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult UnitedStates()
            {
                return View();
            }
        }
    }
  8. In the Solution Explorer, expand Views and expand Shared
  9. Double-click _Layout.cshtml to open it
  10. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Countries Statistics :: @ViewBag.Title</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @Html.ActionLink("Countries Statistics", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Home", "Index", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <p>&copy; @DateTime.Now.Year - Countries Statistics</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
    
  11. To create an indexing class, in the Solution Explorer, right-click Models -> Add -> Class...
  12. Change the Name to States
  13. Click Add
  14. Create and initialize an array as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace CountriesStatistics09.Models
    {
        public class States
        {
            private string[] states;
    
            public States()
            {
                states = new string[30];
    
                states[0]  = "Delaware";     states[1]  = "Pennsylvania";   states[2]  = "New Jersey";
                states[3]  = "Georgia";      states[4]  = "Connecticut";    states[5]  = "Massachusetts";
                states[6]  = "Maryland";     states[7]  = "South Carolina"; states[8]  = "New Hampshire";
                states[9]  = "Virginia";     states[10] = "New York";       states[11] = "North Carolina";
                states[12] = "Rhode Island"; states[13] = "Vermont";        states[14] = "Kentucky";
            }
        }
    }

Creating an Indexer

An indexer, also called an indexed property, is a class@#039;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];
}

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@#039;s 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 to which the property refers, 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]; }
    }
}

If necessary, you use a member of the class to initialize the array. Here is an example:

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

    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;
    }
}

Based on this, a type of formula to create a normal read-only indexed property is:

class class-name
{
    data-type[] array-name = new data-type[length];

    public data-type this[int i]
    {
        get { return array-name[i]; }
    }
}

Practical LearningPractical Learning: Creating an Indexer

Accessing an Element of an Indexed Property

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 the variable of the class. The variable would produce the value stored at that index. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Numbers</title>
</head>
<body>
<h1>Numbers</h1>

@{
    var number = new Number();
}

<p>Number: @number[0]</p>
<p>Number: @number[2]</p>
<p>Number: @number[4]</p>
</body>
</html>

This would produce:

String Comparison

Based on the known number of items of the array, you can use a loop (while, do...while or for) to access element from its indexproperty and assign the desired string to it. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Numbers</title>
</head>
<body>
<h1>Numbers</h1>

@{
    int i = 0;
    var number = new Number();
}

@while(i < 3)
{
    <p>Number @(i + 1): @number[i]</p>
    i++;
}
</body>
</html>

You can also use a foreach loop to visit each member of the property.

Practical LearningPractical Learning: Accessing an Indexed Property

  1. In the Solution Explorer, under Views, right-click Home -> Add -> New Scaffolded Item...
  2. In the Add Scaffold dialog box, in the middle frame, click MVC 5 View
  3. Click Add
  4. Type UnitedStates as the View Name
  5. Click Add
  6. Change the document as follows:
    @{
        ViewBag.Title = "List of States";
        var states = new CountriesStatistics09.Models.States();
    }
    
    <h2 class="text-center">List of States</h2>
    
    <table border="5">
        <tr>
            <td><b>Order of Admission to Union</b></td>
            <td><b>State Name</b></td>
        </tr>
    
        @for (int i = 0; i < 15; i++)
        {
            <tr>
                <td class="text-center">@(i + 1)</td>
                <td>@states[i]</td>
            </tr>
        }
    </table>
  7. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Indexed Properties

  8. Close the browser and return to your programming environment

A String-Based Indexed Property

Introduction to String-Based Indexed Properties

Usually when you create an array, to access an item, youi use its index, which is normally based on an integer. When it comes to indexed properties, you can specify that the members of its array will be accessed through a string.

To create an indexed property where the members of its array can be accessed by a string, in the square brackets of the this property, pass the string as data type followed by a name for the parameter. 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. When defining the indexed property, make sure you return the type of value that used to declare the array. 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;
        }
    }
}

Practical LearningPractical Learning: Creating a String-Based Indexer

  1. In the Solution Explorer, under App_Code, double-click States.cs to access it
  2. To create an indexer that uses strings, change the class as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace CountriesStatistics09.Models
    {
        public class States
        {
            private string[] states;
            private string[] abbreviations;
    
            public States()
            {
                states = new string[15];
                abbreviations = new string[15];
    
                states[0]  = "Delaware";     states[1]  = "Pennsylvania";   states[2]  = "New Jersey";
                states[3]  = "Georgia";      states[4]  = "Connecticut";    states[5]  = "Massachusetts";
                states[6]  = "Maryland";     states[7]  = "South Carolina"; states[8]  = "New Hampshire";
                states[9]  = "Virginia";     states[10] = "New York";       states[11] = "North Carolina";
                states[12] = "Rhode Island"; states[13] = "Vermont";        states[14] = "Kentucky";
    
                abbreviations[0]  = "DE"; abbreviations[1]  = "PA"; abbreviations[2]  = "NJ";
                abbreviations[3]  = "GA"; abbreviations[4]  = "CT"; abbreviations[5]  = "MA";
                abbreviations[6]  = "MD"; abbreviations[7]  = "SC"; abbreviations[8]  = "NH";
                abbreviations[9]  = "VA"; abbreviations[10] = "NY"; abbreviations[11] = "NC";
                abbreviations[12] = "RI"; abbreviations[13] = "VT"; abbreviations[14] = "KY";
            }
    
            public string this[string abbrv]
            {
                get
                {
                    for (int i = 0; i <= states.Length - 1; i++)
                    {
                        if (abbreviations[i] == abbrv)
                        {
                            return states[i];
                        }
                    }
                    
                    return "";
                }
            }
        }
    }

Accessing a String-Based Indexed Property

Once you have defined the property, you can use it. To access any of its elements, you must pass a string to the square brackets as index. You can then do whatever you want with the value produced by the property. For example, you can display it to a visitor. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Students</title>
</head>
<body>
<h1>Students</h1>

@{
    StudentAge sa = new StudentAge();
    float age = sa["Paul Bertrand Yamaguchi"];
}

<p>Student Age: @age</p>
</body>
</html>

This would produce:

String Comparison

Practical LearningPractical Learning: Accessing a String-Based Indexed Property

  1. In the Solution Explorer, under Views and under Home, double-click UnitedStates.cshtml to acccess it
  2. To use the indexed property, change the document as follows:
    @{
        ViewBag.Title = "State Search";
        var states = new CountriesStatistics09.Models.States();
    }
    
    <h2>State Search</h2>
    
    @{
        string strStateName = string.Empty;
        string strAbbreviation = string.Empty;
    
        if (IsPost)
        {
            strAbbreviation = Request["txtAbbreviation"].ToUpper().Replace(" ", "").Replace(".", "");
            strStateName = states[strAbbreviation];
        }
    }
    
    @using (Html.BeginForm())
    {
        <table>
            <tr>
                <td>State Abbreviation:</td>
                <td>@Html.TextBox("txtAbbreviation", @strAbbreviation)</td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="txtFind" value="Find the State" /></td>
            </tr>
            <tr>
                <td>State Name:</td>
                <td>@Html.TextBox("txtStateName", @strStateName)</td>
            </tr>
        </table>
    }
  3. To execute the application, on the main menu, click Debug -> Start Without Debugging:

    String Comparison

  4. In the top text box, an abbreviation for a state. Here is an example:

    String Comparison

  5. Click the button

    String Comparison

  6. Close the browser and return to your programming environment

Indexed Properties of Other Types

Introduction

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. Here is an example:

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";
    }
}

You can then use a variable of the class to access the indexed property. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Philosophers</title>
</head>
<body>
<h1>Philosophers</h1>

@{
    var thinkers = new Philosopher();
}

@for (int i = 0; i < 8; i++)
{
    <p>Philosopher: @thinkers[i]</p>
}
</body>
</html>

This would produce:

String Comparison

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

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;
    }
}

You can then use a variable of the class as an array:

<!DOCTYPE html>
<html>
<head>
<title>Driving Record</title>
</head>
<body>
<h1>Driving Record</h1>

@{
    dynamic driving = new DrivingWhileIntoxicated();
}

@for (int i = 0; i < 7; i++)
{
    <p>Driver Was Intoxicated @(i + 1): @driving[i]</p>
}
</body>
</html>

This would produce:

String Comparison

An Enumeration-Based Indexed Property

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

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];
        }
    }
}

To access the property outside, apply an enumeration member to the square brackets on an instance of the class. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Golf Club Membership</title>
</head>
<body>
<h3>Golf Club Membership</h3>

@{
    dynamic mbr = new GolfClubMembership();
}

<p>Membership Fee: @mbr[CategoryFee.Senior]</p>
</body>
</html>

This would produce:

String Comparison

Topics on Indexed Properties

Multi-Parameterized Indexed Properties

The indexed properties we have used so far were taking only one parameter. You can create an indexed property whose array uses more than one dimension. To start an indexed property that would use various parameters, first create the array. Then create a this property that takes the parameters. Here is an example for an indexed property that relates to a two-dimensional array:

public class Numbers
{
    double[,] nbr;

    public double this[int x, int y]
    {
    }
}

In the body of an accessor (get or set), use the parameter as appropriately as you see fit. At a minimum, for a get accessor, you can return the value of the array using the parameters based on the rules of a two-dimensional array. This can be done as follows:

public class Numbers
{
    double[,] nbr;

    public double this[int x, int y]
    {
        get { return nbr[x, y]; }
    }
}

You can use a method of the class to initialize the array. Here is an example:

public class Numbers
{
    double[,] nbr;

    public double this[int x, int y]
    {
        get { return nbr[x, y]; }
    }

    public Numbers()
    {
        nbr = new double[2, 4];
        nbr[0, 0] = 927.93;
        nbr[0, 1] = 45.155;
        nbr[0, 2] = 2.37094;
        nbr[0, 3] = 73475.25;
        nbr[1, 0] = 186.72;
        nbr[1, 1] = 82.350;
        nbr[1, 2] = 712734.95;
        nbr[1, 3] = 3249.0057;
    }
}

After creating the property, you can access each element of the array by applying the square brackets to an instance of the class. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Numbers</title>
</head>
<body>
<h3>Numbers</h3>

@{
    var nbr = new Numbers();
}

@for (int i = 0; i < 2; i++)
{
    for (int j = 0; j < 4; j++)
    {
        double value = nbr[i, j];

        <p>Number [@i][@j]: @value</p>
    }
}
</body>
</html>

Remember that one of the most valuable features of an indexed property is that, when creating it, you can make it return any primitive type and you can make it take any parameter of your choice. Also, the parameters of a multi-parameter indexed property don't have to be the same type. One can be a character while the other is a bool type, etc. When defining the property, you must apply the rules of both the methods and the arrays. Here is an example of a property that takes an integer and a string:

public class Catalog
{
    private long[] nbrs;
    private string[] names;

    public double this[long nbr, string name]
    {
        get
        {
            if ((nbr == nbrs[0]) && (name == names[0]))
                return 275.25;
            else if ((nbr == nbrs[1]) && (name == names[1]))
                return 18.75;
            else if ((nbr == nbrs[2]) && (name == names[2]))
                return 50.00;
            else if ((nbr == nbrs[3]) && (name == names[3]))
                return 65.35;
            else if ((nbr == nbrs[4]) && (name == names[4]))
                return 25.55;
            else
                return 0.00;
        }
    }

    public Catalog()
    {
        nbrs = new long[5];
        nbrs[0] = 273974;
        nbrs[1] = 539759;
        nbrs[2] = 710234;
        nbrs[3] = 220685;
        nbrs[4] = 192837;
        names = new string[5];
        names[0] = "Women Double-faced wool coat";
        names[1] = "Men Cotton Polo Shirt";
        names[2] = "Children Cable-knit Sweater";
        names[3] = "Women Floral Silk Tank Blouse";
        names[4] = "Girls Jeans with Heart Belt";
    }
}

Here is an example that uses some variables:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
<h3>Department Store</h3>

@{
    var cat = new Catalog();

    var itemNumber = 539759;
    var itemDescription = "Men Cotton Polo Shirt";
    var price = cat[itemNumber, itemDescription];
}

<p>Item #: @itemNumber<br />
Description: @itemDescription<br />
Unit Price: @price</p>
</body>
</html>

This would produce:

String Comparison

In the above example, we first declared the variables to be passed as parameters to the indexed property. You can pass such parameter(s) directly to a variable of the class. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
<h3>Department Store</h3>

@{
    var cat = new Catalog();

    var price = cat[220685, "Women Floral Silk Tank Blouse"];
}

<p>Item #:      220685<br />
Description: Women Floral Silk Tank Blouse<br />
Unit Price:  @price</p>
</body>
</html>

Just as you can create a two-dimensional indexed property, you can also create a property that takes more than two parameters. Once again, it is up to you to decide what type of parameter would be positioned where in the square brackets. Here is an example of an indexed property that takes three parameters:

public class Catalog
{
    public string this[long nbr, string name, double price]
    {
        get
        {
            return "Item #:     " + nbr.ToString() + ", " +
                   "Item Name:  " + name + ", " +
                   "Unit Price: " + price.ToString("C");
        }
    }
}

To access the array stored in the class, after declaring a variable from it, pass the approriate values to its square brackets. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
<h3>Department Store</h3>

@{
    var cat = new Catalog();
}

<p>Item Description: @cat[220685, "Women Floral Silk Tank Blouse", 50.00]</p>
</body>
</html>

Overloading an Indexed Property

An indexer borrows various characteristics of a method. One of them is the ability to create various indexers in the same class but all of them must have the same name: this. Still, the various indexers of a class can return the same type of value. Because of this, when creating the indexers, you must find a way to distinguish them. One way you can do this, as seen with method overloading, consists of passing a different type of parameter to each indexer. This is referred to as overloading.

To overload the this property, if two indexed properties take only one parameter, each must take a different (data) type of parameter than the other. Here is an example:

public class StudentIdentifications
{
    private int[] studentIDs;
    private string[] fullnames;

    // This property takes a student ID, as an integer,
    // and it produces his/her name
    public string this[int id]
    {
        get
        {
            for (int i = 0; i < studentIDs.Length; i++)
                if (id == studentIDs[i])
                    return fullnames[i];

            return "Unknown Student";
        }
    }

    // This property takes a student name, as a string,
    // and it produces his/her student ID
    public int this[string name]
    {
        get
        {
            for (int i = 0; i < fullnames.Length; i++)
                if (name == fullnames[i])
                    return studentIDs[i];

            return 0;
        }
    }

    public StudentIdentifications()
    {
        studentIDs = new int[6];
        studentIDs[0] = 39472;
        studentIDs[1] = 13957;
        studentIDs[2] = 73957;
        studentIDs[3] = 97003;
        studentIDs[4] = 28947;
        studentIDs[5] = 97395;

        fullnames = new string[6];
        fullnames[0] = "Paul Bertrand Yamaguchi";
        fullnames[1] = "Ernestine Ngovayang";
        fullnames[2] = "Patricia L Katts";
        fullnames[3] = "Helene Mukoko";
        fullnames[4] = "Joan Ursula Hancock";
        fullnames[5] = "Arlette Mimosa";
    }
}

To access one of the properties, apply the square brackets to a variable of the class and pass the appropriate type(s) or number of properties. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Students Records</title>
</head>
<body>
<h3>Students Records</h3>

@{
    dynamic std = new StudentIdentifications();
}

<h4>Student Identification</h4>

<p>Student ID: 39472<br />
Full Name:  @std[39472]</p>

<h4>Student Identification</h4>

<p>Full Name:  Joan Ursula Hancock<br />
Student ID: @std["Joan Ursula Hancock"]</p>
</body>
</html>

This would produce:

String Comparison

An indexer combines the features of an array and those of a method that takes one or more parameters. As an array, an indexer can use one or more dimensions as we have seen so far. Borrowing the features of a method, an indexer can take one or more parameters and it can return a value. Besides passing different types of parameters to various indexers, you can create some of them that take more than one parameter. Here is an example:

public class Catalog
{
    private long[] nbrs;
    private string[] names;
    private double[] prices;

    // This property produces the name of an item, as a string,
    // if it is given the item #, as a number
    public string this[long nbr]
    {
        get
        {
            for (int i = 0; i < nbrs.Length; i++)
                if (nbr == nbrs[i])
                    return names[i];

            return "Unknown Item";
        }
    }

    // This property produces the price of the item, as a number,
    // if it is given the item name and its number
    public double this[string name, long nbr]
    {
        get
        {
            for (int i = 0; i < 5; i++)
                if ((nbr == nbrs[i]) && (name == names[i]))
                    return prices[i];

            return 0.00;
        }
    }

    public Catalog()
    {
        nbrs = new long[5];
        nbrs[0] = 273974;
        nbrs[1] = 539759;
        nbrs[2] = 710234;
        nbrs[3] = 220685;
        nbrs[4] = 192837;

        names = new string[5];
        names[0] = "Women Double-faced wool coat";
        names[1] = "Men Cotton Polo Shirt";
        names[2] = "Children Cable-knit Sweater";
        names[3] = "Women Floral Silk Tank Blouse";
        names[4] = "Girls Jeans with Heart Belt";

        prices = new double[5];
        prices[0] = 275.25;
        prices[1] = 18.75;
        prices[2] = 50.00;
        prices[3] = 65.35;
        prices[4] = 25.55;
    }
}

To access the property, declare a variable of the class and pass the appropriate arguments to its square brackets. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Department Store</title>
</head>
<body>
<h3>Department Store</h3>

@{
    var cat = new Catalog();
}

<h4>Item Identification</h4>

<p>Item #:  539759<br />
Unit Price: @cat[539759]</p>

<h4>Item Identification</h4>

<p>Item #:      192837<br />
Description: Girls Jeans with Heart Belt<br />
Unit Price:  @cat["Girls Jeans with Heart Belt", 192837]</p>
</body>
</html>

This would produce:

String Comparison

Read/Write Indexed Properties

Introduction

So far, we have purposely used indexed properties that only produced a value. In some cases, you may want to be able specify the value of an element of the array. To make this possible, you can create an indexed property that uses an array whose values you can specify or change. Other than that, remember that a property that can accept and produce values is called a read-write property.

If you want an indexed property to be read/write, besides the get accessor as we have been using it so far, you should also include a set accessor.

A Read/Write Property of a Primitive Type

To create a read/write indexed property, you should include a set accessor for the property. In the set accessor, assign the value contextual keyword to the field indexed with the this parameter. Here is an example of a read/write indexed property that includes a set accessor:

public class Number
{
    double[] Numbers;

    public double this[int i]
    {
        get { return numbers[i]; }
        set { numbers[i] = value; }
    }
}

After creating the read/write property, you can assign its values outside of the class. In other words, clients of the class can change the values of its elements. Remember that the advantage of an indexed property is that each element of the arrayed field can be accessed from the instance of the class by directly applying the square brackets and the (appropriate) index to it. Here is an example:

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

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

To set the value of an item, access it by its index and assign the desired value to it. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Numbers</title>
</head>
<body>
<h3>Numbers</h3>

@{
    var nbr = new Number();

    nbr[2] = 2.37094;

    for (int i = 0; i < 5; i++)
    {
        <p>Number @(i + 1): @nbr[i]</p>
    }
}
</body>
</html>

This would produce:

String Comparison

Based on this, a type of formula to create a regular read/write indexed property is:

class class-name
{
    data-type[] array-name = new data-type[Index];

    public data-type this[int i]
    {
        get { return array-name[i]; }
        set { array-name[i] = value; }
    }
}

We saw that the index of a property could be a value other than an integer-based. For example, we created an index that was a string type. Here is an example:

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

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

For such a property, if you make it read/write, you can assign its values outside of the class. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Philosophers</title>
</head>
<body>
<h3>Philosophers</h3>

@{
    var thinker = new Philosopher();

    thinker[5] = "Stuart Rachels";
}

@for (int i = 0; i < 8; i++)
{
    <p>Philosopher: @thinker[i]</p>
}
</body>
</html>

This would produce:

String Comparison

The same rules would apply to a read/write indexed property that can receive Boolean or decimal values.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2008-2019, FunctionX Next