Uncommon Collection features : Indexers, Multiple Indexers with Params and yield

Collections are the most used elements in the programs. Indexers helps us to access the elements of a collection. Although you might not have implemented indexers, you have used indexers a lot. Whenever you have an array or a collection object you use indexers.

Implementing indexers is done by coding “this[TYPE]” property. The object implementing the indexer can be any type of object, however the object is mostly a collection object. For simplicity I haven’t implemented as a collection object here. Most of the indexers are integers, but it can be any type of indexer.

C# 2.0 has come with a new keyword “yield”. You can return an enumerable object using yield keyword with the combination of “return” keyword, rather than building the collection and returning it.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
 
namespace properties
{
    class Program
    {
        static void Main(string[] args)
        {
            User u1 = new User();
 
            Console.WriteLine(u1[56]);
 
            User u2 = u1["use","of","indexers", "explained", "with", "multiple", "arguments"];
 
            foreach (string name in u2.GiveUserNames())
            {
                Console.WriteLine(name);
            }
            Console.Read();
        }
    }
 
    public class User
    {
        public string this[int a] // type to return usually the collections element type
        {
            get
            {
                return string.Format("Somebody has called me with index {0}", a);           
            }
        }
 
        private string[] userNames; // just to demonstrate params
        public User this[params string[] items]
        {
            get
            {
                userNames = items; 
                return this;
            }
        }
        public IEnumerable<string> GiveUserNames()
        {
            foreach (string i in userNames)
            {
                yield return i;
            }
        }
    }
}

Output :

Somebody has called me with index 56
use
of
indexers
explained
with
multiple
arguments
_

Those feature are really useful if you are dealing with your own types.

One Comment

  1. Ahmet Tolga Tat says:

    really nice features…

Leave a Reply