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

Properties in C#

In C#, properties are the natural extension of data fields. They are also known as ‘smart field’.
Inside a class, we declare a data field as a private and provide a set of public set and get method to access the data fields, because the data field cannot be accessed directly outside the class so we use get and set methods.

Example:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication38
{
   public class Class1
    {
       
        private int i;
        public int prop
        {
            get
            {
                return i;
            }
       
            set
            {
                i = value;
            }
        }

    }
}

.cs code:
  private void button1_Click(object sender, EventArgs e)
        {
            Class1 obj = new Class1();
            int x = obj.prop;
            x = 10;
            MessageBox.Show(x.ToString());

        }


Output :