Users Pricing

blog

home / developersection / blogs / indexer in c# with example

Indexer in C# with example

Hemant Patel 4046 08 Mar 2017 Updated 17 Mar 2018

The indexer is a class property that’s treated an object as an array. Or in other word indexer is a class property that’s access a class or structure in the same way as arrays.When you define an indexer for a class, then this class behaves similar to virtual array. You also access the instance of an object of this class using array access operator []. The indexer is also similar to a property. You use get and set accessors for defining an indexer. Indexer defines with ‘this’ keyword. It's not defined with names.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
 
namespace Learn
{
    public class Program
    {
        public static void Main()
        {
            StringDataStore stringStore = new StringDataStore();
            stringStore [0] = "First";
            stringStore [1] = "Second";
            stringStore [2] = "Third";
            stringStore [3] = "Fourth";
            for (int i = 0; i < 10; i++)
                Console.WriteLine(stringStore [i]);
            Console.ReadLine();
        }
    }
 
    public class StringDataStore
    {
        private string[] stringArr = new string[10]; // internal data storage
        public StringDataStore()
        {
 
        }
 
        public string this[int indx]
        {
            get
            {
                if (indx < 0 && indx >= stringArr.Length)
                    throw new IndexOutOfRangeException("Cannot store more than 20 bjects");
 
                return stringArr [indx];
            }
           
            set
            {
                if (indx < 0 && indx >= stringArr.Length)
                    throw new IndexOutOfRangeException("Cannot store more than 20 bjects");
 
                stringArr [indx] = value;
            }
        }
    }
}

You can visit useful related post

Indexer in C#

What are indexers in C# .NET?

Is it possible to have a static indexer in C#?

what is difference between indexers and properties?


Hemant Patel

Student

Exploring the online world is my passion. have experience of #content writing #SEO #Digital Marketing #On-Page #Lead Generation #Content Analyst #Marketing Analyst... I could never stop at one point, continuously wanted to acquire more and more skills. My work for any organization will be full of passion and hard work.