C# Indexers

C# Code Snippets Indexers
Share:

About

In this code snippet, we will learn how to implement indexers in C#.

Indexers allow classes to be indexed just like arrays. To retrieve or set a value you just provide an index inside a set of square brackets just like you would for an array.

Let’s see how to implement and use indexers in the code snippet below. 

Code:

using System;

namespace Indexer
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] intArr = new int[5] { 5,2,3,8,7 };

            MyClass MC = new MyClass(intArr);

            //Get element at the third index.
            Console.WriteLine(MC[3]);

            //Set the value using an indexer.
            MC[3] = 20;

            //Lets check the value again.
            Console.WriteLine(MC[3]);

            Console.ReadLine();
        }
    }

    class MyClass
    {
        public int[] IntArray { get; set; }

        public MyClass(int[] intArray)
        {
            IntArray = intArray;
        }

        //Indexer is defined with the "this" keyword.
        public int this[int index]
        {
            get
            {
                return this.IntArray[index];
            }

            set
            {
                this.IntArray[index] = value;
            }
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger