Search This Blog

Monday 29 February 2016

Indexer in c#

Indexers allow class to be used just like an array.

Q. How to create an Indexers?
A. In place of Method name use "this" keyword and in place of () Bracket use [] Square Bracket.

Normal Method = 
public string MethodName(int index)
Indexers      = public string this[int index]

Indexers have get and set accessor.

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

namespace IndexerClass
{
    class IndexerClass
    {
        // Array of string values
        private string[] week = { "Sunday""Monday""Tuesday""Wednesday""Thursday""Friday""Saturday" };

        // Return Array Length
        public int Length
        {
            get
            {
                return week.Length;
            }
        }

        // Indexer declaration
        public string this[int index]
        {
            get
            {
                return week[index];
            }

            set
            {
                week[index] = value;
            }
        }

        // Indexer declaration
        public int this[string name]
        {
            get
            {
                int index = 0;

                while (index < Length)
                {
                    if (week[index] == name)
                    {
                        return index;
                    }
                    index++;
                }
                return index;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            IndexerClass p = new IndexerClass();

            // Use the indexer's get accessor to return value
            for (int i = 0; i < p.Length; i++)
            {
                Console.WriteLine(p[i]);
            }

            // Use the indexer's get accessor to return index
            Console.WriteLine(p["Thursday"]);

            Console.ReadKey();
        }
    }
}

OUTPUT

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
4

Note:-

For More Info visit Microsoft.com

No comments:

Post a Comment