Tuesday, August 26, 2014

Understanding Indexer in C#

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

namespace Apps
{
    class IndexerExample
    {
        //private int[] item = new int[11];

        private string[] nameslist = new string[11];
        private int index = 0; 
        public string this[int index]
        {
            get
            {
                return nameslist[index];
            }
            set
            {
                nameslist[index] = value;
            }
        }

        public int this[string indexContent]
        {
            get
            {
                for (int i = 0; i < nameslist.Length; i++)
                {
                    if (indexContent == nameslist[i])
                    {
                        index = i;
                        break;
                    }
                }
                return index;
            }
            set
            {
                for (int i = 0; i < nameslist.Length; i++)
                {
                    if (indexContent == nameslist[i])
                    {
                        nameslist[i] = value.ToString();
                    }
                }
            }
        }
    }
    class UnderstandingIndexer
    {
        public static void Main()
        {
            IndexerExample obj = new IndexerExample();
            obj[4] = "Nagendra";
            // calls the property with return type string
            Console.WriteLine(obj[4]);

            // calls the property with return type int
            Console.WriteLine(obj["Nagendra"]);
        }
    }
}

Indexer an object to be indexed in the same way as an array. Indexer modifier can be private, public, protected or internal. The return type can be any valid C# types.Indexers in C# must have at least one parameter.

No comments:

Post a Comment