Tech Off Post

Single Post Permalink

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

    dpratt71 said:
    W3bbo said:

    I am at least somewhat acquainted with ReadOnlyCollection. In any case, I consider ReadOnlyCollection vs. IEnumerable as mostly apples vs. oranges. Changing nothing else about your example, what would be the drawback to defining TheCollection as type IEnumerable<Object>?

    I'm assuming you mean like this:

    class Foo { 
    public IEnumerable<Object> TheCollection { get; private set; }
    private List<Object> underlyingCollection;
    public Foo() {
    underlyingCollection = new List<Object>();
    TheCollection = (IEnumerable<Object>) underlyingCollection; 

    In this case, your collection isn't actually read-only.  A user of your library can cast TheCollection back to List<Object> and modify the contents of the list, which is bad in most situations (since you're directly accessing a private data member).