Hi everybody, it's a long time for me to continue the next part of basic C#.
Today, I will talk about indexers. What are the indexers?
Indexers're properties with the outward appearance of array. They allow you to access an object as an array.
You can use indexers if your types contain a collection as a member, indexers will helpful to you to access to the
internal collection in the object conveniently and safely.
Indexers're similar to properties that define a set and get method, but indexers will use this reference and indexers're nameless properties[you will see from an example].
This is an example code of indexer tester.
namespace IndexerTester
{
class Program
{
static void Main(string[] args)
{
People people = new People();
Console.WriteLine(people[1]);
Console.WriteLine(people[0]);
Console.ReadLine();
}
}
public class People
{
private ArrayList people;
public People()
{
people = new ArrayList();
people.Add(new Person("A"));
people.Add(new Person("B"));
people.Add(new Person("C"));
}
public String this[int i]
{
get
{
Person p = people[i] as Person;
return p.FullName;
}
set
{
Person p = people[i] as Person;
p.FullName = value;
}
}
// overloaded indexer
public int this[String str]
{
get
{
int i = 0;
foreach (Person p in people)
{
if(p.FullName.Equals(str,StringComparison.OrdinalIgnoreCase))
return i;
i++;
}
return -1;
}
}
}
public class Person
{
public String FullName { get; set; }
public Person(String str)
{
FullName = str;
}
}
}
You can see that there're 2 indexers in this code
public String this[int i]
{
get
{
Person p = people[i] as Person;
return p.FullName;
}
set
{
Person p = people[i] as Person;
p.FullName = value;
}
}
and...
public int this[String str]
{
get
{
int i = 0;
foreach (Person p in people)
{
if(p.FullName.Equals(str,StringComparison.OrdinalIgnoreCase))
return i;
i++;
}
return -1;
}
}
}
Now, you will see from the code that you can access the collection in your object by (Object)[(index)], and
you can modify value by (Object)[(index)] = (Data).
This is a format of indexers -> public (Type) this[(Type t)] {...}
In the block, there are get or set accessors as properties.
^^ it's very easy right? If you have something to ask about C# or you want me to explain more about basic topics in very details you can post on this site.
I will try my best for your answer as much as I can ^^. CU Sooon for a next topic[you can request to me].
6e2ddec0-9baf-4164-905a-94977a4ed3b2|0|.0