Indexer In C#

C# indexers are commonly known as virtual arrays. A C# indexer is one of the properties of a class that variable can be used to access or use the other member of the same class using the index of an array.  We can say that indexer property is named as class property.
Using the Class Property, we can access a member variable of a class or struct. In C#, indexers will be created using Keyword - “this”. Indexers in C# are applicable on both the following.
1.     classes
2.     structs. 
Syntax:
[Modifier] [returntype] this [argumentList]
{
  get
  {
     // get block
  }
  set
  {
    // set block
  }
}
Example,
#region Indexer in c#

        public class IndexerDemo
        {
            //Int Array
            private int[] testIndexer = new int[3];
            //Declaraing Indexer
            public int this[int index]
            {

                get
                {
                    //Getting Value of Indexer
                    return testIndexer[index];
                }

                set
                {
                    //Setting Value of Indexer
                    testIndexer[index] = value;
                }
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            IndexerDemo indexerDemoObject = new IndexerDemo();

            // Setting Value to Class Array
            for (int i = 0; i < 3; i++)
            {
                indexerDemoObject[i] = i+1;

            }
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("==============Indexer Output Starts===============");
            //appending into string builder of class Array value
            for (int i = 0; i < 3; i++)
            {
                stringBuilder.AppendLine(indexerDemoObject[i].ToString());
            }
            stringBuilder.AppendLine("================Indexer Output Ends==============");

            //prinitng values
            MessageBox.Show(stringBuilder.ToString());
        }
        #endregion



Output


Comments

Popular posts from this blog