SIGN UP MEMBER LOGIN:    
ARTICLE

Indexers in C#

Posted by Ankit Nandekar Articles | C# Language April 22, 2011
C# introduces a new concept known as Indexers which are used for treating an object as an array.
Reader Level:

C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C# community. Defining a C# indexer is much like defining properties. We can say that an indexer is a member that enables an object to be indexed in the same way as an array.

Properties are used for providing access to scalar values of a class like int, float, string etc. Whereas indexers are used for providing access to a value of an array outside the class.

An indexer is defined the same as a property but we don't have any name to as indexers. As it refer to our own class in the place of name we use "this".

Syntax:

[Modifiers] <type> this[<parameters >]
{
[get {<stmts>;}] //get Accessor
[set {<stmts>;}] //set Accessor

}

Where the modifier can be private, public, protected or internal. The return type can be any valid C# types. The 'this' is a special keyword in C# to indicate the object of the current class. The formal-argument-list specifies the parameters of the indexer. The formal parameter list of an indexer corresponds to that of a method, except that at least one parameter must be specified, and that the ref and out parameter modifiers are not permitted. Remember that indexers in C# must have at least one parameter. Other wise the compiler will generate a compilation error.

The following program shows a C# indexer in action

Add a new project with the name IndexerDemo; create class indexer IndexerDemo.cs and give it the following code:


using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
 
namespace
IndexerDemo
{
    class
IndexerDemo
    {
        string[] arr;
        public IndexerDemo(int Size)
        {
           
//Initializing the array under Constructor
            arr = new strint[Size];

 
           
//Assigning Default value to array
            for (int i = 0; i < Size; i++)
           
                arr[i] = "Empty";
           
        }

 
       
//Defining an Indexer to access the values of array which is private outside the class.


        public string this[int index]
        {
            get { return arr[index]; }
            set { arr[index] = value; }
        }
    }
}

Now to access the array using the indexer, write the following code into your main program class:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IndexerDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            IndexerDemo obj = new IndexerDemo(6);
            //Getting the defaulat value of array
            for (int i = 0; i < 6; i++)
            {
                Console.WriteLine(obj[i]);
            }
            Console.WriteLine();
            //Setting the Array with new Values:

            obj[0] = "India";
            obj[1] = "America";
            obj[2] = "Australia";
            obj[3] = "England";

            //Getting the current values of array:

            for (int i = 0; i < 6; i++)
            {
                Console.WriteLine(obj[i]);
            }
            Console.ReadLine();

        }
    }
}


Run Your Project.
 

Login to add your contents and source code to this article
share this article :
post comment
 

Nice article, but what is difference between an array of string and an array of your class? BTW, wrong code in main program. Thanks :-)

Posted by Majid Kamali Apr 23, 2011

Nice article

Posted by Dinkar Chavhan Apr 22, 2011
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Team Foundation Server Hosting
Become a Sponsor