I’m writing an interface which has a collection property which I want to be read only. I don’t want users of the interface to be able to modify the collection. The typical suggestion I’ve found for creating a read only collection property is to set the type of the property to IEnumerable like this:
private List<string> _mylist;
public IEnumerable<string> MyList
{
get
{
return this._mylist;
}
}
Yet this does not prevent the user from casting the IEnumerable back to a List and modifying it.
If I use a Yield keyword instead of returning _mylist directly would this prevent users of my interface from being able to modify the collection. I think so because then I’m only returning the objects one by one, and not the actual collection.
private List<string> _mylist;
public IEnumerable<string> MyList
{
get
{
foreach(string str in this._mylist)
{
yield return str;
}
}
}
Yes, the resulting sequence will be read-only. It also has the advantage of deferred execution, so the loop won’t actually be evaluated until some client code enumerates the items in the sequence (although this can have unexpected consequences if the internal collection is changed before the client code tries to enumerate it).