Search This Blog

Thursday, July 18, 2013

Indexers C#

C# > Indexers

Indexers enable to create a class that client applications can access as an array.
Implementation: encapsulate an internal collection or array.





Example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        class Test
        {
            private string[] mStr = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "K"};
            public int Length
            {
                get { return mStr.Length; }
            }
            // Indexer declaration.
            public string this[int index]
            {
                get
                {
                    return mStr[index];
                }
                set
                {
                    mStr[index] = value;
                }
            }
        }
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            Test t = new Test();
            //  indexer set accessor
            t[1] = "a";
            t[2] = "b";
            //  indexer get accessor
            for (int i = 0; i < t.Length -1 ; i++)
            {
                MessageBox.Show(t[i]); 
            }
        }
     }
}