xMichal
xMichal

Reputation: 644

C# Type as object with indexer

Consider a situation: I have a method which use DataRow:

public void MyMethod (DataRow input)
{
    DoSomething(input["Name1"]);
}

But now I have some another input types with indexer which I want to pass to this method. St like:

public void MyMethod (AnyTypeWithIndexer input)
{
    DoSomething(input["Name1"]);
}

But I haven't found anything like that. I tried IDictionary but it didn't work. Is there any super type st like "Indexable" or anything with which I can replace the "AnyTypeWithIndexer"?

Note: I still need this method to pass the DataRow and also my custom class (which I want to implement).

Can anybody help?

Thanks.

Upvotes: 2

Views: 165

Answers (2)

Heinzi
Heinzi

Reputation: 172280

No, unfortunately, there is no interface that automatically applies to "all classes with an indexer that takes a string argument and returns an object".

What you can do, however, is to create a "proxy class" that implements such an interface yourself:

public interface IStringToObjectIndexable
{
    object this[string index] { get; set; }
}

class DataRowWrapper : IStringToObjectIndexable
{
    private readonly DataRow row;

    public DataRowWrapper(DataRow row) => this.row = row;

    public object this[string index]
    {
        get => row[index];
        set => row[index] = value;
    }
}

MyMethod can now be declared as follows:

public void MyMethod(IStringToObjectIndexable input)
{
    DoSomething(input["Name1"]);
}

// Compatibility overload
public void MyMethod(DataRow input) => MyMethod(new DataRowWrapper(input));

Upvotes: 5

Oleksandr Tolstikov
Oleksandr Tolstikov

Reputation: 350

You can use dynamic type, but you will need to be noticed about the disadvantages of dynamic, such as performance drawbacks because of DLR, and the fact that type safety should be on your shoulders

    public class WithIndexer
    {
        public int this[string key] => 42;
    }

    public static async Task Main()
    {
        Dictionary<string, int> a = new Dictionary<string, int>();
        a.Add("meow", 41);

        Foo(a, "meow");
        Foo(new WithIndexer(), "key");
    }

    private static void Foo(dynamic indexed, string key)
    {
        Console.WriteLine(indexed[key]);
    }

Output:

41
42

Upvotes: 1

Related Questions