0

I have a class as follows:

public class Document
{
    public List<DocumentSection> sections = new List<DocumentSection>();
    ...

Various questions cover the situation where a property needs to be writable from inside the class but readonly from outside it (http://stackoverflow.com/questions/4662180/c-sharp-public-variable-as-writeable-inside-the-clas-but-readonly-outside-the-cl)

I'd like to do the same but for this collection - allow adding to it from within the class, but only allow a user to iterate through it when they are outside it. Is this elegantly doable?

Thanks

Glinkot
  • 2,924
  • 10
  • 42
  • 67

5 Answers5

2

Expose the collection as IEnumerable so that users can only iterate through it.

public class Document {
   private List<DocumentSection> sections;

   public IEnumerable<DocumentSection> Sections 
   { 
       get { return sections; }
   }
}
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
1

Yes, you have to hide the List and only expose an Add method and a property of type IEnumerable<DocumentSection>:

public class Document
{
    private List<DocumentSection> sections = new List<DocumentSection>();

    public void AddSection(DocumentSection section) {
        sections.Add(section);
    }

    public IEnumerable<DocumentSection> Sections {
        get { return sections; }
    }
}
Jan
  • 15,802
  • 5
  • 35
  • 59
1

You could expose the List as an IEnumerable<DocumentSection> and only use the List internally. Like so:

public class Document {
  public IEnumerable<DocumentSection> Sections { get { return list; } }
  private List<DocumentSection> list;
}
Oliver Salzburg
  • 21,652
  • 20
  • 93
  • 138
0

If you really want to allow only iteration, you could keep the IList private, but make a public function resolving to GetEnumerator()

Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
0
public class Document {
   private readonly List<DocumentSection> sections = new List<DocumentSection>();

   public IEnumerable<DocumentSection> Sections 
   { 
       get 
       { 
           lock (this.sections)
           {
               return sections.ToList(); 
           }
       }
   }
}