Total Pageviews

Thursday, 15 December 2011

Indexer in C#

By means of indexer you can index to your class object.I would say it nothing but an array.More flexible to accessing the class simple array syntax.

Look at snap No.1 : Here indexer Demo object is created as ' i ' of class Indexer.



Look at snap No.2 : Here I am trying to assign value 5 at perticuler index [3] of Object ' i ' of class Indexer.


Look at snap No.3 : How value is going to set at set {..} accessor of  ' this ' indxer place, at class Indexer.



Look at snap No.4 : Value 5 assingned at perticuler index [3] of Object ' i ' of class Indexer.



Look at snap No. 5 : Here I am trying to assign value 6 at perticuler index [5] of Object ' i ' of class Indexer.



Look at snap No. 6 : How value is going to set at set {..} accessor of  ' this ' indxer place, at class Indexer.



Look at snap No. 7 : Value 6 assingned at perticuler index [5] of Object ' i ' of class Indexer.



Look at snap No. 8 : for loop rotation to reach at last index position at intArray[..] decleared at Indexer class.That will print 11 number of time from 0 - 10 at commond prompt.


Look at snap No. 9 : Here set values are returning from get {..} accessor of  indexer ' this ' place at Indexer class.

 



Look at snap No. 10 : Values are set at prefered index location of Object ' i ' of class indexer.


  Look at snap No. 10 : Indexer Output at Command prompt.




Copy Full Code:
namespace ConsoleApplication1
{
    class Indexer
    {

        int[] intArray = new int[11];

        public int this[int index]
        {

            get
            {

                return intArray[index];

            }

            set
            {

                intArray[index] = value;

            }

        }


        public class Demo
        {

            static void Main(string[] args)
            {

                Indexer i = new Indexer();

                i[3] = 5;

                i[5] = 6;



                for (int j = 0; j <= 10; j++)
                {

                    Console.WriteLine("Value at Index of [{0}]={1}", j, i[j]);

                }

                Console.ReadKey();

            }

        }

    }


}

No comments:

Post a Comment