Indexing classes with access modifiers...
So I am pretty sure that I have the term right, but I was writing some code for a Winforms application and came across some code that I was unfamiliar with, and it related to using [index] to index a class.
So the concept is this:
I have a class, say Customers() and the customer has a Name, phone number, and a customer id. The phone number is unique, as well as the customer id. I saw a bit of code like this:
customers[phonenumber]
and the phonenumber is a string. I know that you can do it with a DataSet and it's tables, but I never thought that you could do it with a class (I have been away from OOP too long before the advent of C#).
So I looked at the class and found that you could override the functionality of the [] indexers.
So in essence I have this in my class:
public Customer this[int index]
{
get { return (Customer)List[index]; }
}
public Customer this[string PhoneNumber]
{
get
{
foreach(Customer m in List)
{
if(m.PhoneNumber == PhoneNumber)
{
return m;
}
}
return null;
}
}
This gives me the ability to have a phone number and find the Customer based on that as an index instead of something that I made up to be a unique key.
The other key to this is that the Customers class inherited from the CollectcionBase class so that List was inherent and you had access to a Collection in which to use the indexers.
Have a happy day.