Tech Off Post

Single Post Permalink

View Thread: How about some syntax sugar for IEnumerable<>?
  • User profile image

    dpratt71 said:
    wkempf said:
    While ReadOnlyCollection<T> may be fine for "managing" a read-only collection, I don't think it a good choice for exposing a read-only collection. For one thing, ReadOnlyCollection<T> implements IList<T>, which, of course, has methods/properties for modifying the collection.

    Another point in favor of IEnumerable<> that I forgot to mention is flexibility. In other words, you're able to change the implementation later on and perhaps choose a different underlying container.

    I'm not sure what you mean when you say "...they are also less meaningful...". Why? If you program in C#, then you are very accustomed to using symbols to refer to various concepts. Even terms like "object" and "int" are really symbols representing some "real" type. I'm proposing that there be a symbol that means "some number of things".
    ReadOnlyCollection implements IList<T>'s members only explicitly, so they are inaccessible when the ROC is not cast as an IList<T>, and even then every mutator operation throws an exception.

    ROC is meant to be a Decorator wrapper around another list (which can be modified). I think ROCs work best with C#'s auto-implemented properties:

    class PublicFacingCollection : ReadOnlyCollection<Object> { // I often alias generic types like this for readability and semantics

    class Foo {

    public PublicFacingCollection TheCollection { get; private set; }

    private List<Object> underlyingCollection;

    public Foo() {

    underlyingCollection = new List<Object>();

    TheCollection = new PublicFacingCollection(underlyingCollection); // the PublicFacingCollection instance no-longer needs to be dealt with by the Foo owner class. The underlyingCollection can be modified and the changes shown up in the TheCollection property instantly. Consumers of the Foo type do not see any mutator methods of the ROC as they are implemented explicitly.