Read-only list or unmodifiable list in .NET 4.0

C#Java.NetReadonly Collection

C# Problem Overview


From what I can tell, .NET 4.0 still lacks read-only lists. Why does the framework still lack this functionality? Isn't this one of the commonest pieces of functionality for domain-driven design?

One of the few advantages Java has over C# is this in the form of the Collections.unmodifiablelist(list) method, which it seems is long overdue in IList<T> or List<T>.

Using IEnumerable<T> is the easiest solution to the question - ToList can be used and returns a copy.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

For those who like to use interfaces: .NET 4.5 adds the generic IReadOnlyList interface which is implemented by List<T> for example.

It is similar to IReadOnlyCollection and adds an Item indexer property.

Solution 3 - C#

How about the ReadOnlyCollection already within the framework?

Solution 4 - C#

If the most common pattern of the list is to iterate through all the elements, IEnumerable<T> or IQueryable<T> can effectively act as a read-only list as well.

Solution 5 - C#

In 2.0 you can call AsReadOnly to get a read-only version of the list. Or wrap an existing IList in a ReadOnlyCollection<T> object.

Solution 6 - C#

Solution 7 - C#

Create an extension method ToReadOnlyList() on IEnumerable, then

IEnumerable<int> ints = new int[] { 1, 2, 3 };
var intsReadOnly = ints.ToReadOnlyList();
//intsReadOnly [2]= 9; //compile error, readonly

here is the extension method

public static class Utility
{
	public static IReadOnlyList<T> ToReadOnlyList<T>(this IEnumerable<T> items)
	{
		IReadOnlyList<T> rol = items.ToList();
		return rol;
	}
}

see Martin's answer too

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris SView Question on Stackoverflow
Solution 1 - C#LukeHView Answer on Stackoverflow
Solution 2 - C#MartinView Answer on Stackoverflow
Solution 3 - C#Jason WattsView Answer on Stackoverflow
Solution 4 - C#Ana BettsView Answer on Stackoverflow
Solution 5 - C#Paul AlexanderView Answer on Stackoverflow
Solution 6 - C#Matthew DresserView Answer on Stackoverflow
Solution 7 - C#Rm558View Answer on Stackoverflow