views:

551

answers:

3

I'm trying to derive from List and selectively turn the IsReadOnly property on and off. I was hoping that the Add/Remove/[] functions would honor this property, but they don't. What's the right way of doing this?

My derived class has some additional properties, so I can't unfortunately just wrap the list in ReadOnlyCollection.

+1  A: 

You could call the "AsReadOnly" method on list which should return to you an IList instance that should honor that it is...err...read-only.

...OK, I just read your last sentence, my bad. In which case maybe you just want to implement the IList interface or any friend and just route most of the interface to a list you keep internally. Then you can build this behaviour. Even so, I would do a similar pattern, provide some "AsReadOnly" method that explicitly gives you something that is read-only.

flq
+7  A: 

Use encapsulation instead of inheritance in this case.

You should just make your class implement IList<T>, and have a private List<T> variable.

You can pass through any functions you wish, but also can completely override them, change behavior, etc. This gives you complete control (at the expense of having many methods that does nothing but call this.List.method(...) ).

In general, I don't think it's a good idea to inherit from the BCL collection classes in any case. I prefer to make them an implementation detail internal in my class.

Reed Copsey
+2  A: 

List<T> is by definition a mutable type. There's no way to make it read-only.

If you're making a derived class, you should probably be implementing IList<T> directly rather than subclassing List<T> anyway. This will give you full control over the implementation, allowing you to make it read-only if you wish.

Levi