Reputation: 331260
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?
Upvotes: 0
Views: 541
Reputation: 45127
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
Upvotes: 0
Reputation: 273494
It is by design, exposing members is only done when (absolutely) necessary, to let the object maintain a correct state at all times. And it is not a good idea to expose a field (_items) as protected, that would require a protected property. In this case, there already is a public property (this[])
Composition will give you even less access - no protected members either.
Upvotes: 1
Reputation: 180868
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.
Upvotes: 1
Reputation: 564641
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.
Upvotes: 7
Reputation: 30418
List<T>
isn't designed to be a base class. You should use one of the classes in System.Collections.ObjectModel instead.
Upvotes: 2