Manuel
Manuel

Reputation: 11469

How to get the size (number of elements) of an indexer class object?

Given a function which accepts a parameter with the following interface:

interface ITest
{
    String this[Int32 dataId, Int32 rowId] { get; set; }
}

How can I determine the number of elements in each dimension of the indexer?

For example if a function receives an array one could use the .GetUpperBound method:

Int32 GetSizeOfDimension(Array test, Int32 dimension)
{
    return test.GetUpperBound(dimension);
}

I'm trying to do the following:

    Int32 GetSizeOfDimension(ITest test, Int32 dimension)
    { 
        // return UBound of test's given dimension
    }

Upvotes: 1

Views: 646

Answers (2)

Guffa
Guffa

Reputation: 700362

You can't.

Although the indexer is usually used to access a collection using a continuous index, there isn't really anything that limits it to that. The method might for example only return valid values for the parameters (1,2), (45,188), (-78,129837123) and (0,1000). Specifying bounds for those values would be pointless.

If you want to be able to get the bounds from the interface, you have to add properties or methods for that in the interface, so that the class implementing the interface can supply the size depending on how the interface is implemented.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500665

You can't, in the general case. Imagine an indexer which "worked" in every single case except one - which was randomly determined at the start of the program. How would you find that case, other than by brute force?

If you need this information, your interface will have to expose it directly.

Upvotes: 2

Related Questions