Read-Only and Unmodifiable List in C#
This post will discuss how to read-only, immutable, unmodifiable List in C#.
To get a read-only view of a list, we can use the ReadOnlyCollection<T> class. The following code example demonstrates its usage. It creates a List<T> of integers and then wraps the list in a ReadOnlyCollection<T>.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.ObjectModel; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; ReadOnlyCollection<int> immutableList = new ReadOnlyCollection<int>(nums); Console.WriteLine(String.Join(", ", immutableList)); // 1, 2, 3, 4, 5 } } |
Note that the ReadOnlyCollection<T> class is a read-only view over the specified list. Therefore, any changes made to the underlying list are reflected in the read-only list.
Alternatively, you can use the List<T>.AsReadOnly() convenience method to get a read-only IList<T> generic interface implementation that wraps the original list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; IList<int> immutableList = nums.AsReadOnly(); Console.WriteLine(String.Join(", ", immutableList)); // 1, 2, 3, 4, 5 } } |
That’s all about read-only, unmodifiable List in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)