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;
}
}
}