Indexers are a new concept in C#. Indexers enable a class object to function as an array. Implementing indexers is similar to implementing properties using the get and set functions. The only different is that when you call an indexer, you pass an indexing parameter. Accessing an indexer is similar to accessing an array. Indexers are nameless, so the this keyword declares indexers.
I just said that after defining indexers, a class object could be treated as an array. What does that mean? To explain, I‘ll show you an example using the class called my class. The way you treat an instance of myClass now is like this:
myClass cls = new myClass(); cls.MaleGender = true;
After defining an indexer in myClass, you could treat an instance of it as if it were an array:
myClass cls = new myClass(); cls[0].MaleGender = true; cls[1].MaleGender = true;
You define indexer by using the this keyword as if were an array property of type object.
public object this[int index] { get { if (! ValidIndex(index)) throw new Exception("Index out of range."); else return MaleGender(index).Value; } set { if (!ValidIndex(index) ) throw new Exception("Index out of range."); else MaleGender(index).Value = value; } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|