C# Indexers


This entry is part 2 of 2 in the series C# Indexers

What is an indexer? An indexer is a way to access elements in a class that represent a list of values. We have already used indexes in Arrays and Lists. Why would we need to implement indexers? Sometimes in our classes we have collection semantics. We use key-value pairs. We use a dictionary. What is a dictionary? A dictionary is a data type that resides in the System.Collections.Generic and it uses a hash table to store data. A hash table is fast. It looks up items by the key.

If you have a list of objects and you want to look them up by a key as opposed to an index, you should use a dictionary. If you have a list of objects and you would like to look them up by an index (an integer) then a List is a better choice.

How do we declare an indexer? An indexer is nothing but a property. Instead of an identifier we use the this keyword.

    public class Customer
    {   // a customer might not be the best example of a Dictionary.
        private readonly Dictionary<string, string> _dictionary;
        // instead of initializing in the constructore we could:
        // private Dictionary<string, string> _dictionary = new Dictionary,string,string>();
        public DateTime ExpiryDate { get; set; }

        public Customer()
        {   // initialize in the constructor
            _dictionary = new Dictionary<string, string>();
        }
        public string this[string key]
        {
            get { return _dictionary[key]; }
            set { _dictionary[key] = value; }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var customer = new Customer();
            customer["name"] = "Mosh";
            customer["lastname"] = "Hamedani";
            Console.WriteLine(customer["name"]);
            Console.ReadKey();
        }
    }

Series Navigation<< C# Indexers Introduction