How to create an empty IReadOnlyCollection

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

Why IReadOnlyCollection has ElementAt but not IndexOf

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

Read-only list or unmodifiable list in .NET 4.0

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.

ReadOnlyCollection or IEnumerable for exposing member collections?

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