Skip to main content

Indexers in C#

Definition of Indexers from MSDN
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

Whenever you are accessing individual element from List<T> or Hashtable<T,T> etc you are using Indexers.
For example
List<string> str=new List<string>();
str.Add("Rameez");
str.Add("Usmani");
string firstName=str[0];  //[0] is implying that you are calling indexer on instance of List class

How Indexer is added to a class

To add an indexer to a class you have to expose a property named "this(actually a keyword)" followed by "data type of index" in square brackets. Like this
public ReturnDataType this[indexDataType]
{
    get { //logic to return the correct value }
    set { //logic to set the correct value }
}
Lets say you have collection of Students and you want to access Student by name using Indexer , here is how it can be done

public Student this[string Name]
{
    get
    {
         Student std=GetFromCollectionByName(Name);
         return std;
    }
}

To understand how to implement indexers we will create a class as an example. We will make a class University which has collection of Departments (DepartmentCollection) . DepartmentCollection class will expose indexer to retrieve department by name or index.

Here it is how
public class Department
{
    public string Name {get;set;}
    public string Code {get;set;}
}
public class DepartmentCollection
{
    private List<Department> depts=new List<Department>(); 
    public Department this[string dpName]
    {
        get
        {
             for (int a=0;a<depts.Count;a++)
             {
                  if (depts[a].Name.CompareTo(dpName)==0)
                  {
                       return depts[a];
                  }
             }
             return null;
        }
    } 
    public Department this[int dpIndex]
    {
        get
        {
             return depts[dpIndex];
        }
    }
public class University
{
    private DepartmentCollection depts=new DepartmentCollection(); 
    public DepartmentCollection Departments
    {
        get { return depts; }
    }
}
Now lets see how simply we can access a department in a University class. Right now for simplicity we are not concerned how Departments collection is filled.
University ui=new University();
 Department dept=ui.Departments[0];
//or
Department dept=ui.Departments["CSIT"];

More about Indexers
Indexers (C# Programming Guide) - MSDN
Using Indexers (C# Programming Guide) - MSDN
Comparisons Between Properties and Indexers (C# Programming Guide) - MSDN

Comments

Popular posts from this blog

Multithreaded C# TCP server to handle multiple clients

I decided to write a minimal multithreaded TCP based server as a blog post. Following class can serve as a skeleton for any small or large scale multithreaded TCP socket server. It do not contain much error handling , it is only to give an idea that how multithreaded server works and how it can process multiple clients using threading. using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Collections.Generic; namespace RandomStuffMine { public class MTServer {     public int Port{get;set;}     public Socket ServerSocket{get;set;}     private List<Client> Clients=new List<Client>();     private bool runServer=true;     public MTServer(int port)     {         Port=port;         ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);     }   ...

Decoding JPEG image file using libavcodec

I got a chance to work on a video encoding application that decodes series of jpeg files and convert them into ogg theora video file. I used the infamous libavcodec library that is used in FFMPEG . I decided to write blog posts explaining how I decode jpeg images and convert them into ogg video file. This is the first part and in this I will explain how to decode jpeg images using libavcodec. To learn how to write decoded images as a ogg video file please read http://random-stuff-mine.blogspot.com/2017/07/encoding-raw-images-to-ogg-theora-video.html Before reading this blog post you must be aware of using and setting up libavcodec. I highly recommend this tutorial to get basics of using libavcodec http://www.ffmpeg.org/doxygen/0.6/api-example_8c-source.html Allocating input format context We will first allocate input format for reading the file. We will use avformat_open_input function that will allocate AVFormatContext structure passed to it , the function detects input typ...

Encoding raw images to Ogg Theora video using libavcodec

In one of the blog posts we learned how to decode jpeg images using libavcodec. This is the second part of that post. In this we will learn how to encode decoded images (raw images) to theora and write them in ogg video file. In the end of the first part we saved our raw image in raw_data variable and its length in raw_data_size variable. Lets assume that we packaged all our decoding code in one function called "decode_jpeg_image" which has following signature int decode_jpeg_image(char *filename,int file_name_size,uint8_t *raw_data,int *raw_data_size) filename = name of jpeg file to decode file_name_size = length of jpeg file's name raw_data = contains decoded raw image on return raw_data_size = contains length of raw_data on return Now let's start working on how to encode this image in raw_data to theora and write that image to ogg video file. Finding Theora encoder We first have to find encoder for THEORA which is represented by AVCodec structure. He...