Sunday, August 23, 2009

Indexed Properties


Indexed properties

Indexed properties allow array like access on an object and there's also support for a default indexed property - essentially a nameless property which lets you directly use [] on the object. Below example features both named and default index properties. I believe C#ers call indexed properties as indexors so perhaps you might see these two words used interchangeably.

ref class R { private:     Hashtable^ h; public:     R()     {         h = gcnew Hashtable();     }      //Named property      property int Age[String^]     {     protected:         int get(String^ s)         {             if(h->ContainsKey(s))             {                 for each(DictionaryEntry de in h)                 {                     if(s->CompareTo(de.Key) == 0)                         return (int)de.Value;                 }             }             return 0;         }              void set(String^ s, int age)         {             h->Add(s,age);         }     }      //Default property      property int default[String^]     {         int get(String^ s)         {             return Age[s];         }          void set(String^ s, int age)         {             Age[s] = age;         }     }     };

It took me more than an hour to figure out what the extra parameter in the set() method of an indexed property. It turns out that it is the right hand term when you attempt to modify a property.


R SomeClass = gcnew R();
int RightHandTerm = 10;
String ^LeftHandTerm = "No Name";

SomeClass->Age[LeftHandTerm] = RightHandTerm; //assignment to property Age,
//Set() method will be called

then, the parameters in the set method set() method:

void set(String^ s, int age)
will correspond to: s=LeftHandTerm, age=RightHandTerm