24 Jun

C# ReadOnly Wrapper Collection

This examples shows how to create a readonly wrapper collection. If you have a private collection in a class and you only want to access as readonly, you can use AsReadOnly method in “List” generic class in System.Collections.Generic namespace. This method says that “I don’t want people to be able to modify the list content.” It returns a read-only wrapper collection.

Also you can expose your list through a property of type IEnumerable. ( “AsReadOnly” method is mentioned above is prefered.)

Sample Usage:

    public class ReadOnlyCollectionExample
    {
        private List<string> _collection = new List<string>();
        public IList<string> Collection1
        {
            get
            {
                return _collection.AsReadOnly();
            }
        }

        // Adding is not allowed - only iteration
        public IEnumerable<string> Collection2
        {
            get { return _collection; }
        }
    }