How can I access a element of a IReadOnlyCollection through it index?
Use the ElementAt(int) function with the index value. Here is the MSDN link to the ElementAt(int) function https://msdn.microsoft.com/en-us/library/bb299233(v=vs.110).aspx
Use the ElementAt(int) function with the index value. Here is the MSDN link to the ElementAt(int) function https://msdn.microsoft.com/en-us/library/bb299233(v=vs.110).aspx
EDIT: The new .Net 4.6 adds an API to get an empty array: Array.Empty<T> and arrays implement IReadOnlyCollection<T>. This also reduces allocations as it only creates an instance once: IReadOnlyCollection<int> emptyReadOnlyCollection = Array.Empty<int>(); What I ended up doing is mimicking the implementation of Enumerable.Empty using new TElement[0]: public static class ReadOnlyCollection { public static IReadOnlyCollection<TResult> … Read more
IReadOnlyCollection is a collection, not a list, so strictly speaking, it should not even have ElementAt(). This method is defined in IEnumerable as a convenience, and IReadOnlyCollection has it because it inherits it from IEnumerable. If you look at the source code, it checks whether the IEnumerable is in fact an IList, and if so … Read more
Use collections.Mapping e.g. import collections class DictWrapper(collections.Mapping): def __init__(self, data): self._data = data def __getitem__(self, key): return self._data[key] def __len__(self): return len(self._data) def __iter__(self): return iter(self._data)
You’re looking for ReadOnlyCollection, which has been around since .NET2. IList<string> foo = …; // … ReadOnlyCollection<string> bar = new ReadOnlyCollection<string>(foo); or List<string> foo = …; // … ReadOnlyCollection<string> bar = foo.AsReadOnly(); This creates a read-only view, which reflects changes made to the wrapped collection.
More modern solution Unless you need the internal collection to be mutable, you could use the System.Collections.Immutable package, change your field type to be an immutable collection, and then expose that directly – assuming Foo itself is immutable, of course. Updated answer to address the question more directly Is there any reason to expose an … Read more