Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a readonly copy of a collection

I have a class that contains a collection. I want to provided a method or property that returns the contents of the collection. It's ok if calling classes can modify the individual objects but I do not want them adding or removing object from the actual collection. I have been copying all the objects to a new list, but now I'm thinking that I could just return the list as IEnumerable<>.

In the simplified example below is GetListC the best way to return a read only version of a collection?

public class MyClass
{
    private List<string> mylist;

    public MyClass()
    {
        mylist = new List<string>();
    }

    public void Add(string toAdd)
    {
        mylist.Add(toAdd);
    }

    //Returns the list directly 
    public List<String> GetListA 
    { 
        get
            {
            return mylist;
            }
    }

    //returns a copy of the list
    public List<String> GetListB
    {
        get
        {
            List<string> returnList = new List<string>();

            foreach (string st in this.mylist)
            {
                returnList.Add(st);
            }
            return returnList;
        }
    }

    //Returns the list as IEnumerable
    public IEnumerable<string> GetListC
    {
        get 
        {
            return this.mylist.AsEnumerable<String>();
        }

    }

}
like image 927
Eric Anastas Avatar asked May 12 '09 17:05

Eric Anastas


1 Answers

You can use List(T).AsReadOnly():

return this.mylist.AsReadOnly()

which will return a ReadOnlyCollection.

like image 66
Joey Avatar answered Oct 09 '22 07:10

Joey