views:

143

answers:

4
class NewList<T> : List<T>

Why can't I access it's internals like T[] _items, etc?

Why aren't they protected, but private?

Should I use composition for this?

+2  A: 

List<T> isn't designed to be a base class. You should use one of the classes in System.Collections.ObjectModel instead.

Andy
THanks, do you know why didn't MS seal the class?
Joan Venge
@Joan: I think they made a mistake in not sealing it, personally. I don't know why they didn't choose to do so, but it would've matched the guidelines better if they had.
Reed Copsey
That I don't know. It definitely would've made the situation much clearer, though.
Andy
@Reed: Yep, and I think the only reason it's not sealed now is it would break [bad] code that [assumed it made sense to] derives from it.
280Z28
+7  A: 

They're private because the author (Microsoft) did not intend for you to access them, probably for safety reasons.

You should use composition instead of inheritance. Make your class expose IList<T> instead of List<T> directly.

List<T> should never be directly exposed in a public API (this is actually specified in the design guidelines). It should be used as an internal implementation detail only.

Reed Copsey
I don't think they are 'safety' reasons, more like 'correctness'
Henk Holterman
One of the main goals of proper api and encapsulation is a form of safety - you are protecting your own implmentation from the outside world.
Reed Copsey
+1  A: 

Why can't I access it's internals like T[] _items, etc?

Reflector says _items is private. The underscore suggests a private member

Why aren't they protected, but private?

In the case of _items, Microsoft provides the public ToArray method. It returns _items.

Robert Harvey
Thanks. I know that method but that would be a huge penalty for my collection, as it would create an extra collection because of accessibility.
Joan Venge
Yes, that is true.
Robert Harvey
It actually returns the underlying storage or a copy of? Does this mean if you mod the items in the ToArray-ed array, the contents of the list change?
spender
No, it's a copy of the actual array. So your changes will not affect the original.
Joan Venge
A: 

You don't need it. That is, what can you do with _items that you can't do with the Item : T property? They have given you a simple, functional abstraction to the underlying array with the indexer. It is very light weight -- all it does it check the bounds and increment the version of the list (on the setter) ...

var lst = new List<int>() { 1, 2, 3, 4, 5 };
lst[0].Dump(); // 1
lst.Dump(); // 1, 2, 3, 4, 5
lst[0] = 2;
lst.Dump(); // 2, 2, 3, 4, 5
JP Alioto