Sunday, June 14, 2015

C# - Indexers

Indexers allow you to use an index on an object to obtain the values stored within the object. The behavior of the indexers is similar to properties; we use get and set methods for define indexers. Properties return a specific data member while indexer returns a particular value from the object.
Properties are defined by the properties name while defining the indexers we use this keyword. Indexers modifier cab be public private, protected or internal. Indexer must have at least one parameter.

Example.   - using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication39
{
   public class Class1
    {
       string[] s = new string[3];
       public string this[int index]
       {
           get
           {
               return s[index];
           }
           set
           {
               s[index] = value;
           }
       }

    }
}


.cs code - 

private void button1_Click(object sender, EventArgs e)
        {
            Class1 obj = new Class1();
            obj[1] = "Sachin";
           MessageBox.Show(obj[1]).ToString();
          

        }

Output -



                                                                   Author:Sachin Pathak

1 comment: