Babu Kumarasamy
Babu Kumarasamy

Reputation: 329

How to access the indexer with Interface Explicitly implemended

When we explicitly implement an interface for an indexer, how can we able to set and get value form the indexer after creating object. or inside the same class constructor

namespace oopsTesting.Indexer
{
    public interface IndexerInterface
    {
        char this[int index] { get; set;}
    }

    class Indexer : IndexerInterface
    {
        string name = "Babu Kumarasamy";
        StringBuilder sbName = new StringBuilder("Babu Kumarasamy");

        public Indexer()
        {
            for (int i = 0; i < sbName.Length; i++)
            {
                //How to access the indexer here
                Console.WriteLine("Property Indexer: {0}, StringBuilder: {1}", this[i], sbName[i]);
            }
        }
        char IndexerInterface.this[int index]
        {
            get { return name[index]; }

            set
            {
                //Property or indexer 'string.this[int]' cannot be assigned to -- it is read only
                //Strings are immutable which is why there's no setter, you can however use a string builder:
                //name[index] = value; 

                sbName[index] = value;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            GenericIndexerTest objGenIndexer = new GenericIndexerTest();
            //How to access the indexer here
        }
    }
}

Upvotes: 0

Views: 144

Answers (2)

Jamiec
Jamiec

Reputation: 136114

(Note: This answer assumes GenericIndexerTest inherits Indexer in your code)

The same way as you access any explicitly implemented interface, by casting to the interface type:

GenericIndexerTest objGenIndexer = new GenericIndexerTest();
((IndexerInterface)objGenIndexer)[0] = 'A';

or code to the interface, not the implementation:

IndexerInterface objGenIndexer = new GenericIndexerTest();
objGenIndexer[0] ='A';

Upvotes: 1

Patrick Hofman
Patrick Hofman

Reputation: 156978

You can create a new instance of Indexer, assigning it to a variable of type IndexerInterface:

IndexerInterface ii = new Indexer();
char c = ii[0];

Upvotes: 1

Related Questions