views:

90

answers:

1

I have a (dump) question regarding VB/C#

I often use third party classes where I can access a child object with only specifying the id or key.

Example:

Instead of writing:

DataRow row = GetAPopulatedDataRowSomeWhere();
Object result = row.Items[1]; // DataRow has no Items property
Object result = row.Items["colName"]; // Also not possible

I use this code to access the members:

DataRow row = GetAPopulatedDataRowSomeWhere();
Object result = row[1];
Object result = row["colName"];

Can someone tell me how a class has to look like to support this syntax? My own class has a Dictionary that I want to access this way.

MyClass["key"]; // <- that's what I want
MyClass.SubItems["key"]; // <- that's how I use it now
+11  A: 

You need to have an indexed property.

public class MyClass
{
    public object this[string key]
    {
        get { return SubItems[key]; }
        set { SubItems[key] = value; }
    }
}
Darin Dimitrov
Thanks a lot. That was the cue I needed.
SchlaWiener