Translate

C# Indexers

C# Indexers is a simple implementation of key/value pairs using Dictionary type. Below is a sample implementation of a telephone directory -

TelephoneDirectory class
using System.Collections.Generic;
 
namespace Indexers
{
    public class TelephoneDirectory
    {
        private readonly Dictionary<string, string> _dictionary = 
                              new Dictionary<string, string>();
 
        public string this[string key]
        {
            get { return _dictionary[key]; }
 
            set { _dictionary[key] = value; }
        }
    }
}

As seen above, we use the 'this[]' notation to create the public property that sets/returns indexed value.

We implement TelephoneDirectory as below in the main program -
using System;
 
 
namespace Indexers
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var contact = new TelephoneDirectory();
 
            contact["name"] = "John";
 
            contact["number"] = "3433433434";
 
            Console.WriteLine("{0}'s phone number is {1}", 
               contact["name"], contact["number"]);
        }
    }
}

See how the variable contact could be used as an array holding key value pairs which is just suitable for holding information such as needed for a telephone directory!


C# Indexers