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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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 :

1
2
3
4
5
6
7
8
9
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.