INDEXERS IN C#

                              

We have see what are properties in C# ,now moving on to the indexers in C#.

The work of indexers is same as properties lets revise what properties does , Properties are used to initialize or to read that is read write operations on private data of class. As we have seen that the data members of class are private by default in C# so they aren't allowed to be accessed outside the class.Hence we used property for accesing the data members of class in properties we had get and set accessor methods get to read and set to initialize , to overwrite, values of the data member of class.

Now moving on to the indexers the work of indexers is the same as properties but they are used for accessing the array type variables which are the part of class ,indexers also have the get and set accessor in it the work of get and set accessor is same as in properties to read and write the variables values respectively.

Taking an example to get the concept clear

Before that we take the syntax....

public int this [int x]//name of the indexer is this for storing the refrence data type is the type of                                       the array you want to initialize int[x] where the index is passed 
{
   set
  {
   s[x]=value; \\value is the implicit default argument.
  }
  get
  {
  return s[x];
  }
}

Example


class stack
{
int[] s;

stack()
{
}

public stack(int n)
{
s=new int[n];
}
public int this [int x] //external argument for index datatype integer as index is always in                                                 integer cannot be 1.5 or anything
{
get
{
  if(x<s.Length)
  returns s[x];
  return 0;
}
set 
{
if(x<s.Length)
s[x]=value;
}
}
}

class test
{
public static void Main()
{
stack st=new stack(5); // constructor called and array initlialized
for (int i=0;i<5;i++)
System.Console.WriteLine("enter value);
st[i]=int.parse(Console.ReadLine());  // set accessor of indexer called.
}

for (int i=0;i<5;i++)      // get accessor called of indexer
{
Console.WriteLine(st[i]);
}
}
}



Comments

Popular posts from this blog

State space search / blocks world problem by heuristic approach /TIC TAC TOE

Navigation in Vaadin.

Drag and drop items from one Grid to another