Is using YIELD a read-only way to return a collection?

Posted by Eric on Stack Overflow See other posts from Stack Overflow or by Eric
Published on 2010-05-03T23:23:33Z Indexed on 2010/05/03 23:28 UTC
Read the original article Hit count: 338

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about properties