- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Array.LastIndexOf(T[], T) Method in C#
- The toArray(T[] a) T method of Java AbstractCollection class
- The toArray(T[]) method of AbstractSequentialList in Java
- The toArray(T[] a) method of CopyOnWriteArrayList in Java
- Why can't static method be abstract in Java?
- Getting class of given method using T-code SE80 in SAP
- Short Time ("t") Format Specifier in C#
- Long Time ("T") Format Specifier in C#
- Frog Position After T Seconds in C++
- Why final variable doesn't require initialization in main method in java?
- Why can't we define a static method in a Java interface?
- Handshakes That Don't Cross in C++
- C++ Program to implement t-test
- Why can't we use the "super" keyword is in a static method in java?
- Find minimum s-t cut in a flow network in C++

Advertisements