Indexers

Indexers

Definition

In simple words Indexers are used for classes to act as arrays i.e. allowing classes to be indexed. 

Code

Indexers.cs

class Indexers<T>
 {
        private T[] myIndexerArray;
        public Indexers(int dataSize)
        {
            myIndexerArray = new T[dataSize];
        }
        public int getSize()
        {
            return myIndexerArray.Count(); 
        }
        public T this[int t]
        {
            get { return myIndexerArray[t]; }
            set {  myIndexerArray[t] = value; }
        }
 }

Program.cs

 static void Main(string[] args)
 {
            Indexers<int> indObj = new Indexers<int>(10);

            Console.WriteLine("Send Data: ");
            for (int i = 0; i<indObj.getSize(); i++)
            {
                Console.WriteLine("{0}. {1}", i, (1000 - i));
                indObj[i] = 1000 - i;
            }

            Console.WriteLine("\r\nGet Data: ");

            for (int i = 0; i < indObj.getSize(); i++)
            {
                Console.WriteLine("{0}. {1}", i, indObj[i]);
            }

            Console.ReadLine();

 } 

Output


Explanation

Indexer is similar to a .Net property i.e. you can user get and set for defining an indexer. Usually properties will return a state of a specific object or set it and indexers returns or sets a particular value from the object instance. In simple words it will break the instance of a given object into number of small units and indexes every part of it so it can get or set each part.

Following code use a this keyword to define an indexer:
 public T this[int t]
 {
            get { return myIndexerArray[t]; }
            set {  myIndexerArray[t] = value; }
 }

Comments

Popular posts from this blog

Azure - Manage Blob Storage - Part #7 - Add Metadata to an Existing Container using C#

Azure - Manage Blob Storage - Part #5 - Create Folder Structure and upload a file to folder using an Existing Container using C#

Algorithm - Breadth First Search(BFS) - Python(3)