Search code examples
.nettextflowdocumentrandom-accessindexer

Why does InlineCollection not offer an Indexer (without casting)?


I am using InlineCollection, which acts like an ordered collection.

It implements the IList interface, implying that it is suited for random access of items. However, the indexer defined by that interface is provided only as an explicit interface implementation (meaning that expressions of type InlineCollection need to be cast to IList to use the indexer).

While the documentation does not mention anything specific (it just seems to contain the default text for the list indexer), and my own tests did not seem to exhibit any unexpected behaviour, I am now worried the indexer is not made directly accessible for a reason, for example, that under some circumstances, items in the list are automatically merged or split.

Is there a specific reason why the indexer of InlineCollection should not be used, or did the API just happen to end up like this and we have to accept the explicit cast?

EDIT: For .NET 3.0 and .NET 3.5, the documentation even still explicitly advised against using the indexer:

This type or member supports the Windows Presentation Foundation (WPF) infrastructure and is not intended to be used directly from your code.

EDIT2: To emphasize the issue; I could use the LINQ extension methods for enumerables such as ElementAt, but depending on the implementation, those methods may well take advantage of an indexer if they can cast the object to IList, so I am wondering whether even these extension are safe to use with InlineCollection.


Solution

  • Really interesting question.

    I think that it is hidden because of some specific behavior, but I could not find any reference as well. You can check the source code of the TextElementCollection class and you will see that in line 564 the index operator is implemented but as a private method.

    Source Code

    Of course that we could analyze the source code and check if the usage will result in unexpected behavior..