Illustrates the use of an indexer : Indexer « Class Interface « C# / C Sharp






Illustrates the use of an indexer

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

/*
  Example10_11.cs illustrates the use of an indexer
*/

using System;


// declare the Car class
class Car
{

  // declare two fields
  private string make;
  private string model;

  // define a constructor
  public Car(string make, string model)
  {
    this.make = make;
    this.model = model;
  }

  // define the indexer
  public string this[int index]
  {
    get
    {
      switch (index)
      {
        case 0:
          return make;
        case 1:
          return model;
        default:
          throw new IndexOutOfRangeException();
      }
    }
/*    set
      {
      switch (index)
      {
        case 0:
          this.make = value;
          break;
        case 1:
          this.model = value;
          break;
        default:
          throw new IndexOutOfRangeException();
      }
    }*/
  }

}


public class Example10_11
{

  public static void Main()
  {

    // create a Car object
    Car myCar = new Car("Toyota", "MR2");

    // display myCar[0] and myCar[1]
    Console.WriteLine("myCar[0] = " + myCar[0]);
    Console.WriteLine("myCar[1] = " + myCar[1]);

    // set myCar[0] to "Porsche" and myCar[1] to "Boxster"
    Console.WriteLine("Setting myCar[0] to \"Porsche\" " +
      "and myCar[1] to \"Boxster\"");
    myCar[0] = "Porsche";
    myCar[1] = "Boxster";
    // myCar[2] = "Test";  // causes IndeXOutOfRangeException to be thrown

    // display myCar[0] and myCar[1] again
    Console.WriteLine("myCar[0] = " + myCar[0]);
    Console.WriteLine("myCar[1] = " + myCar[1]);

  }

}

           
       








Related examples in the same category

1.indexed properties
2.Indexer with complex logic
3.Use an indexer to create a fail-soft arrayUse an indexer to create a fail-soft array
4.Overload the FailSoftArray indexerOverload the FailSoftArray indexer
5.Indexers don't have to operate on actual arraysIndexers don't have to operate on actual arrays
6.Two dimensional indexer
7.A two-dimensional fail-soft arrayA two-dimensional fail-soft array
8.Create a specifiable range array classCreate a specifiable range array class
9.Define indexerDefine indexer
10.Indexer: allow array like indexIndexer: allow array like index
11.illustrates the use of an indexer 1illustrates the use of an indexer 1
12.Implements an indexer in a classImplements an indexer in a class
13.Implements an indexer and demonstrates that an indexer does not have to operate on an arrayImplements an indexer and demonstrates that an indexer does not have to operate on an array
14.C# Properties and Indexers
15.Indexing with an Integer IndexIndexing with an Integer Index
16.Indexing with an String Index
17.Indexing with Multiple ParametersIndexing with Multiple Parameters
18.Return class object from indexer