This method is used to return a read-only wrapper for the specified array.
Syntax:
public static System.Collections.ObjectModel.
ReadOnlyCollection<T> AsReadOnly<T> (T[] array);
Here, T is the type of element of the array.
Return Value: This method return the a read-only ReadOnlyCollection<T> wrapper .
Exception: This method throws ArgumentNullException if the array is null.
Below are the examples to illustrate the Array.AsReadOnly(T[]) Method:
Example 1:
using System;
using System.Collections.Generic;
public class GFG {
public static void Main()
{
String[] myArr = { "Sun" , "Mon" , "Tue" , "Thu" };
Console.WriteLine( "Initial Array:" );
PrintIndexAndValues(myArr);
IList<String> myList = Array.AsReadOnly(myArr);
Console.WriteLine( "Read-only Array: " );
PrintIndexAndValues(myList);
}
public static void PrintIndexAndValues(String[] myArr)
{
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine( "{0}" , myArr[i]);
}
Console.WriteLine();
}
public static void PrintIndexAndValues(IList<String> myList)
{
for ( int i = 0; i < myList.Count; i++) {
Console.WriteLine( "{0}" , myList[i]);
}
}
}
|
Output:
Initial Array:
Sun
Mon
Tue
Thu
Read-only Array:
Sun
Mon
Tue
Thu
Example 2:
using System;
using System.Collections.Generic;
public class GFG {
public static void Main()
{
try {
String[] myArr = null ;
IList<String> myList = Array.AsReadOnly(myArr);
Console.WriteLine( "Read-only Array:" );
PrintIndexAndValues(myList);
}
catch (ArgumentNullException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
public static void PrintIndexAndValues(String[] myArr)
{
for ( int i = 0; i < myArr.Length; i++) {
Console.WriteLine( "{0}" , myArr[i]);
}
Console.WriteLine();
}
public static void PrintIndexAndValues(IList<String> myList)
{
for ( int i = 0; i < myList.Count; i++) {
Console.WriteLine( "{0}" , myList[i]);
}
}
}
|
Output:
Exception Thrown: System.ArgumentNullException
Reference: