indexer_concept_1.htm |
- Indexers enable objects to be indexed in a
similar way to arrays.
- A get accessor returns a value. A
set accessor assigns a value.
- The
this keyword is used to define the
indexers.
- The
value keyword is used to define the value
being assigned by the set indexer.
- Indexers do not have to be indexed by an
integer value; it is up to you how to define
the specific look-up mechanism.
- Indexers can be overloaded.
- Indexers can have more than one formal
parameter, for example, when accessing a
two-dimensional array.
|
|
- Indexers in C#, appears very similar to Property, with parameters.
- Can be used as arrays in Class or Struct
- Enables the objects to be sterilized and retrieved with an index.
- contains get ( that keeps tract of the index) and "set" handles the
corresponding values.
- Accessors
- get accessors
- set accessors
|
|
using System;
//csc indexers_concept_1.cs
//here <custome_index> is a Generics type.
namespace ex_indexer_1
{
class test_indexers<custom_index>
{
private custom_index[] arr = new custom_index[100];
public custom_index this[int i]
{
get
{
Console.WriteLine("get array Index : {0}", i);
return arr[i];
}
set
{
arr[i] = value;
Console.WriteLine("\tset value {0}",arr[i] = value);
} }
}
class test {
static void Main()
{
test_indexers<string> str = new test_indexers<string>();
test_indexers<string> str1 = new test_indexers<string>();
str[0] = "Hello, World";
System.Console.WriteLine(str[0]);
Console.ReadLine();
System.Console.WriteLine("---view like array--");
str1[0] = "Hello";
str1[1]= "world";
System.Console.WriteLine("{0}{1}{2}",str1[0],"-",str1[1]);
Console.ReadLine();
}
}
}
|
In the above code "<custom_index>", acts as a class constructor. See this
example Link.
|
|
|