How to write a class that can be accessed without naming it

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

I often use third-party classes, where I can access the child by specifying only an identifier 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 elements:

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

Can someone tell me what the class should look like to support this syntax? My own class has a dictionary that I want to access this way.

MyClass["key"]; // <- that what I want
MyClass.SubItems["key"]; // <- that how I use it now
+3
source share
1 answer

You must have an indexed property .

public class MyClass
{
    public object this[string key]
    {
        get { return SubItems[key]; }
        set { SubItems[key] = value; }
    }
}
+11
source

Source: https://habr.com/ru/post/1738923/


All Articles