Concept of Indexer
Indexer allow/enables an object to access the member of that class using an
index notation.
- Indexer exits only in C#.
- If we want to use our object as an array we need to create indexer in our
class.
or
If we want to use member variable our class to be indexed like an
array for that object, this can be done by indexer. - Use for security purpose so that no one can access our private variable.
- It contain two
accessors set & get.
Syntax
this
[Parameter]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}
Properties of Indexer
- Indexer increase usability.
- Indexer may be abstract.
- Indexer modifier can be private, public, protected or internal.
- Indexer are uniquely identified by their parameters.
- Indexer support inheritance.
- The
return type can be any valid C# types.
- Indexers in C# must have at least one parameter. Else the compiler will
generate a compilation error.
- Outsider can't access & see that member of our class. In this case we are
doing operator overloading of ( [ ] )subscripts.
Program
using
System;
namespace
IndexerExample
{
class
IndexExEmp
{
string name;
string contact_no;
string add;
public string
this[string
Data]
{
get
{
switch (Data)
{
case
"Name": return
name;
case
"Contact_no":
return contact_no;
case
"Address": return
add;
default:
return "wrong
property name";
}
}
set
{
switch (Data)
{
case
"Name": name =
value; break;
case
"Contact_no": contact_no =
value; break;
case
"Address": add =
value; break;
}
}
}
public string
this[int i]
{
get
{
switch (i)
{
case 1:
return name;
case 2:
return contact_no;
case 3:
return add;
default:
return "wrong
index";
}
}
set
{
switch (i)
{
case 1: name =
value; break;
case 2: contact_no =
value; break;
case 3: add =
value; break;
}
}
}
public static
void Main(string[]
aa)
{
IndexExEmp e =
new IndexExEmp();
e[1] = "Deepak dwij";
e["add"] =
"Govindpuram";
e[2] = "9555918764";
Console.WriteLine("the
out put is looks like\n e[1] : {0}, e[2] : {1} & e[\"add\"] : {2} ",
e[1], e[2], e["add"]);
Console.ReadLine();
}
}
}
Output
Disadvantage
Indexers are slower than arrays.