Pages

Tuesday, May 21, 2013

Indexers in C#

1.By ussing indexer we can read and modify the data present in a private array.
2.Indexers enable object to be indexed in a similar manner to array.
3.In indexer a get accessor returns a value .A set accessor assigns a value.
4.The 'THIS' keyword is used to define the indexers.
5.The value keyword is used to define the value being assigned by the set indexer
6.Indexer do not have to be indexed by an integer value.It is upto you how to define the specific look-up mechanism.
7.Indexer can be overloaded and also we can override.
8.We can not create static indexers but we can create static properties.

Sample Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Indexers : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      A a =new A();
        string s1=a.Y;
        a.Y="palleTech";
        int r1=a[2];     // data accesser array position 2
        a[0]=8500;    // modify array value in position 0,800-8500
    }
}
public class A
{
    private int[] sal = new int[3] { 800, 900, 1000 };
    private string y = "palle";
    public string Y
    {
        get
        {
            return Y;
        }
        set
        {
            y = value;
        }
    }
    public int this[int x]
    {
        get
        {
            return sal[x];
        }
        set
        {
            sal[x] = value;
        }
    }
}


No comments:

Post a Comment