The NET indexer USES method instance code

  • 2020-09-16 07:26:45
  • OfStack

Indexer feature

1. Return value of get accessor. The set accessor assigns values.
2. The this keyword is used to define indexers.
3. The value keyword is used to define the value assigned by the set indexer.
4. Indexers do not have to index based on integer values; it is up to you to define a specific lookup mechanism.
5. Indexers can be overloaded.
6. Indexers can have multiple parameters, such as when accessing 2-dimensional arrays.
7. Indexers enable objects to be indexed in a manner similar to arrays.

Code sample


class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get
        {
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        SampleCollection<string> stringCollection = new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}


Related articles: