- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Array.AsReadOnly(T[]) Method in C#
The Array.AsReadOnly(T[]) method in C# returns a read-only wrapper for the specified array, which is the read-only ReadOnlyCollection<T>.
Syntax
public static System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly<T> (T[] array);
Here, T is the type of the elements of the array, whereas array T[] is the one-dimensional zero-based array.
Let us now see an example to implement the Array.AsReadOnly(T[]) method −
Example
using System; using System.Collections.Generic; public class Demo { public static void Main() { String[] arr = { "John", "Tom", "Katie", "Brad" }; // read-only IList wrapper IList<String> list = Array.AsReadOnly( arr ); // Display the values of the read-only IList. Console.WriteLine( "Initial read-only IList..." ); display( list ); // Let us now change the read-only wrapper try { list[0] = "Kevin"; list[1] = "Bradley"; } catch ( NotSupportedException e ) { Console.WriteLine(e.GetType()); Console.WriteLine(e.Message ); Console.WriteLine(); } Console.WriteLine( "After changing two elements, the IList remains the same since it is read-only..." ); display( list ); } public static void display( IList<String> list ) { for ( int i = 0; i < list.Count; i++ ) { Console.WriteLine(list[i] ); } Console.WriteLine(); } }
Output
This will produce the following output −
Initial read-only IList... John Tom Katie Brad System.NotSupportedException Collection is read-only. After changing two elements, tthe IList remains the same since it is read-only... John Tom Katie Brad
Advertisements