Alex Rivera | Logout

Return collection as read-only

Asked 2008-09-10T23:43:35.577
24

I have an object in a multi-threaded environment that maintains a collection of information, e.g.:

public IList<string> Data 
{
    get 
    {
        return data;
    }
}

I currently have return data; wrapped by a ReaderWriterLockSlim to protect the collection from sharing violations. However, to be doubly sure, I'd like to return the collection as read-only, so that the calling code is unable to make changes to the collection, only view what's already there. Is this at all possible?

Edit
Report

2 Answers

35

If your underlying data is stored as list you can use List(T).AsReadOnly method.
If your data can be enumerated, you can use Enumerable.ToList method to cast your collection to List and call AsReadOnly on it.

answered 2008-09-10T23:47:57.783
3

One should note that aku's answer will only protect the list as being read only. Elements in the list are still very writable. I don't know if there is any way of protecting non-atomic elements without cloning them before placing them in the read only list.

answered 2008-09-11T00:22:24.860

Your Answer