Enhanced C#
Language of your choice: library documentation
|
A read-only list indexed by an integer. More...
A read-only list indexed by an integer.
Member list:
The term "source" means a read-only collection, as opposed to a "sink" which is a write-only collection.
IListSource was created before .NET's IReadOnlyList but was later retrofitted so that IListSource implements IReadOnlyList. In addition, IListSource supports slices through its Slice() method, and it has TryGet
methods to eliminate the need to call Count
before reading from the list.
I have often wanted to access the "next" or "previous" item in a list, e.g. during parsing, but it inconvenient if you have to worry about whether the the current item is the first or last. In that case you must check whether the array index is valid, which is both inconvenient and wasteful, because the list class itself will check the array index a second time, and then the .NET runtime will check the index a third time when reading the internal array. The TryGet(index, defaultValue)
extension method can be used to return a default value if the index is not valid, using only one interface call.
Design footnote: Ideally the return type of TryGet would be Maybe<T>, but that design would not allow T to be covariant (out T). Therefore, the version of TryGet
that returns Maybe<T> is an extension method.
Using Impl.ListSourceBase<T> as your base class can help you implement this interface more quickly.
Public Member Functions | |
IRange< T > | Slice (int start, int count=int.MaxValue) |
Returns a sub-range of this list. More... | |
Public Member Functions inherited from Loyc.Collections.ITryGet< int, T > | |
V | TryGet (K key, out bool fail) |
Gets the item for the specified key or index, and does not throw an exception on failure. More... | |
Additional Inherited Members | |
Properties inherited from Loyc.Collections.IIndexed< int, T > | |
V | this[K key] [get] |
Gets the value associated with the specified key. More... | |
IRange<T> Loyc.Collections.IListSource< out out T >.Slice | ( | int | start, |
int | count = int.MaxValue |
||
) |
Returns a sub-range of this list.
start | The new range will start at this index in the current list (this location will be index [0] in the new range). |
count | The desired number of elements in the new range, or int.MaxValue to get all elements until the end of the list. |
ArgumentException | The start index was below zero. |
The (start, count) range is allowed to be invalid, as long as start is zero or above.
this.Count - start
. Implementation note: do not compute (start + count) because it may overflow. Instead, test whether (count > this.Count - start). Most collections should use the following implementation:
IRange<T> IListSource<T>.Slice(int start, int count) { return Slice(start, count); } public Slice_<T> Slice(int start, int count) { return new Slice_<T>(this, start, count); }
Referenced by Loyc.Collections.NegListSource< T >.Slice().