Class Indexer

An indexer creates an illusion that the class itself works like an array.
An indexer allows instances of a class to be indexed like an array.
C# has always had the notion of an indexer that you can add to a class to overload the [ ] operator.
This sense of indexer is called the default indexer since it is not given a name and calling it requires no name.
Indexers can be virtual
Indexers cannot be static
This lets you use array syntax to access the class
An indexer is accessed using the [] operator
They should only be used when an array-like abstraction makes sense



An indexer is a member that enables an object to be indexed in the same way as an array


class Something 
{
   public string this[int number]
   {
      get { return _values[number]; }
      set { _values[number] = value; }
   }
}

This allows you to use the values

class Something 
{
   private string[] _values = new string[100];

   public string this[string name]
   {
      get
      {
         foreach (string str in _values)
         {
             if (str == name) { return (str); }
         }
      }
      set
      {
         for (int n=0; n < _values.Length; n++)
         {
            if (_values[n] == name) { _values[n] = value; return; }
          }
      }
   }
}




© 2019 Better Solutions Limited. All Rights Reserved. © 2019 Better Solutions Limited TopPrev