Indexers in C#

This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

Indexers, another nifty feature of C#, are similar to the overloaded [] (array subscript) operator in C++. An indexer allows you to access a class instance in terms of a member array.

Please refer to C# Language Specification (http://msdn.microsoft.com/en-us/library/aa645596(VS.71).aspx) for more details and recent updates to the C# language.

An indexer declaration may include a set of attributes; a new modifier; a valid combination of the public, private, protected, and internal access modifiers; and one of the virtual, override, or abstract modifiers.

The type of an indexer declaration specifies the element type of the indexer introduced by the declaration. Unless the indexer is an explicit interface member implementation, the type is followed by the keyword this. For an explicit interface member implementation, the type is followed by an interface type, a period (.), and the keyword this. Unlike other members, indexers do not have user defined names.

The formal parameter list of an indexer corresponds to that of a method, with two differences: at least one parameter must be specified, and the ref and out parameter modifiers are not permitted.

The accessors specify the executable statements associated with reading and writing indexer elements.

Even though the syntax for accessing an indexer element is the same as that for an array element, an indexer element is not classified as a variable. Thus, it is not possible to pass an indexer element as a ref or out parameter.

It is an error for an indexer accessor to declare a local variable with the same name as an indexer parameter. With these differences in mind, all rules defined in apply to indexer accessors as well as property accessors.

Indexers and properties, although very similar in concept, differ in the following ways:

  • A property is identified by its name whereas an indexer is identified by its signature.
  • A property is accessed through a simple-name or a member-access whereas an indexer element is accessed through an element-access.
  • A property can be a static member whereas an indexer is always an instance member.
  • A get accessor of a property corresponds to a method with no parameters whereas a get accessor of an indexer corresponds to a method with the same formal parameter list as the indexer.
  • A set accessor of a property corresponds to a method with a single parameter named value whereas a set accessor of an indexer corresponds to a method with the same formal parameter list as the indexer, plus an additional parameter named value.

To understand these concepts, refer to the code in Listing 5.56.

Listing 5.56: Indexer Example


// indexer example, to get DNS aliases for a given IPAddress


using
System;
using
System.Net;
class
GetDNSaliases
{
    string[] m_arrAlias;
    public void Fetch(string strHost)
    {
        IPHostEntry iphe = Dns.GetHostByAddress(strHost);
        m_arrAlias = iphe.Aliases;
    }
    public string this[int nIndex] //indexer
    {
        get
        {
            return m_arrAlias[nIndex];
        }
    }
    public int Count // property
    {
        get { return m_arrAlias.GetUpperBound(0); }
    }
}


class
MyApp
{
    public static string str1;
    public static void Main()
    {
        GetDNSaliases myGetDNSaliases = new GetDNSaliases();
        do
        {
            try
            {
                Console.WriteLine(@"write a valid IP Address and press ENTER (to exit enter
""q"").");
                if ((str1 = Console.ReadLine()) == @"q")
                {
                    break;
                }
                myGetDNSaliases.Fetch(str1);
                Int32 nCount = myGetDNSaliases.Count;
                Console.WriteLine("Found {1} aliases for IP {0}", str1, nCount);

                for (Int32 i = 0; i < nCount; i++)
                {
                    Console.WriteLine(myGetDNSaliases[i]);
                }
            }
            catch (Exception e)
            {               
                    Console.WriteLine("Exception occurred!{0}\r\n", e.ToString());
            }
            finally
            {
                //final code to be executed
            }
        } while (true);
        Console.ReadLine();
    }
}


The code in this listing generates the display in Figure 5.16.

Figure5.16.gif

Figure 5.16: Screen Output Generated from Listing 5.56

Conclusion


Hope this article would have helped you in understanding indexer  in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.


Recommended Free Ebook
Similar Articles
C# Corner
C# Corner started as an online community for software developers in 1999.