Friday, February 11, 2011

Indexers in C#





Using Indexers in C#

Indexer is one of the advanced concepts in C# and much powerful as well..
Indexers are realy easy. They allow your class to be used just like an array. On the inside of a class, you manage a collection of values any way you want. These objects could be a finite set of class members, another array, or some complex data structure. Regardless of the internal implementation of the class, its data can be obtained consistently through the use of indexers.

Following is a generic sample program


public class MySampleCollection<T>
    {
        // Declare an array to store the data elements.
        private const int MAX_SIZE = 100;
        private T[] arr = new T[MAX_SIZE];

        public T this[int index]
        {
            get {
                if (index >= 0 && index < MAX_SIZE)
                {
                   
                    return arr[index];
                }
                else
                {
                    throw new IndexOutOfRangeException();
                }
            }

            set
            {
                if (index >= 0 && index < MAX_SIZE)
                {
                    arr[index] = value;
                }
                else
                {
                    throw new IndexOutOfRangeException();
                }
            }
            
         
        }
       
    }
    class Program
    {
        static void Main(string[] args)
        {
            // Declare an instance of the SampleCollection type.
            MySampleCollection<string> stringCollection = new MySampleCollection<string>();

            // Use [] notation on the type.
            stringCollection[0] = "Hello, World";
            System.Console.WriteLine(stringCollection[0]);
            
        }
    }

2 comments:

  1. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net training in chennai velachery | dot net training institute in velachery

    ReplyDelete
  2. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.
    Dot Net Training in chennai | dot net training center in chennai

    ReplyDelete