CSharp - interface with Indexer

Introduction

The following code are implementing an interface implicitly with indexers.

The key distinction between an interface indexer and a class indexer.

  • An interface indexer does not have a body.
  • An interface indexer does not have modifiers.

Demo

using System;

interface IMyInterface
{
    int this[int index] { get; set; }
}
class MyClass : IMyInterface
{
    //private int[] myIntegerArray;
    private int[] myIntegerArray = new int[4];
    public int this[int index]
    {/*  www .ja v a  2 s .c o m*/
        get
        {
            return myIntegerArray[index];
        }
        set
        {
            myIntegerArray[index] = value;
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        MyClass obMyClass = new MyClass();
        obMyClass[0] = 10;
        obMyClass[1] = 20;
        obMyClass[3] = 30;
        for (int i = 0; i < 4; i++)
        {
            Console.WriteLine("Element #{0} = {1}", i, obMyClass[i]);
        }
    }
}

Result

Related Topic