Indexed Properties

An Indexed Property or Indexer Property creates an illusion that the class itself works like an array.
Indexers provide a way to access elements that encapsulate a list or dictionary of values.
They are similar to properties but they are accessed with an index, not a property name
The string class has a built-in indexer that lets you access each of its 'char' values using an 'int' index

string myText = "Better"; 
Console.WriteLine(myText[0]); // 'B'


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

C# does not allow you to create 'named' indexed properties.
There are no plans to include the ability to declare your own properties that take parameters.
Instead of using an indexed property you should use a type with an indexer which is returned by a property.
The property is there to get access to an object and belongs to the parent object.
The indexer is used to enumerate through an object and belongs to the returned object.



© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext