In this article, we will discuss the Array.AsReadOnly(T) method in C# with its syntax, parameter, and examples.
What is the Array.AsReadOnly<T>(T) method?
This method is used to return the read-only wrapper for the provided array. The Array is a helpful tool provided by the System, specifically the.NET framework in C#.The AsReadOnly(T) method.collections.ObjectModel is the namespace. With the help of this technique, we can provide an existing array for a read-only wrapper that offers an immutable and controlled view of the array's contents.
Syntax:
It has the following syntax:
public static System.Collections.ObjectModel.
ReadOnlyCollection<T> AsReadOnly<T> (T[] array);
Parameters:
- In this case, T denotes the array's element type.
- The value returned by this method is a read-only wrapper for a ReadOnlyCollection .
Exception:
The method throws ArgumentNullException in the event that the array is null.
Example 1:
Let us take an example to illustrate the Array.AsReadOnly(T) method in C#.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Demonstrating LastIndexOf method...");
string[] vehicles = { "car", "bike", "truck", "bus", "motorcycle" };
Console.WriteLine("Array elements:");
// Printing elements of the array
for (int i = 0; i < vehicles.Length; i++)
{
Console.Write("{0} ", vehicles[i]);
}
Console.WriteLine();
// Finding the last occurrence of "bus" in the array
int lastIndex = Array.LastIndexOf(vehicles, "bus");
Console.WriteLine("Last occurrence of 'bus' is at index = " + lastIndex);
}
}
Output:
Demonstrating LastIndexOf method...
Array elements:
car bike truck bus motorcycle
Last occurrence of 'bus' is at index = 3
Example 2:
Let us take another example to illustrate the Array.AsReadOnly(T) method in C#.
using System;
using System.Collections.ObjectModel;
class Program
{
static void Main(string[] args)
{
// Create a regular array
int[] numbers = { 1, 2, 3, 4, 5 };
// Create a read-only wrapper around the array
ReadOnlyCollection<int> readOnlyNumbers = Array.AsReadOnly(numbers);
// Attempting to modify the read-only collection will result in a runtime exception
// readOnlyNumbers.Add(6); // This will throw an exception
// Accessing elements is allowed
Console.WriteLine("First element: " + readOnlyNumbers[0]);
// Looping through elements
Console.Write("Elements: ");
foreach (int num in readOnlyNumbers)
{
Console.Write(num + " ");
}
}
}
Output:
First element: 1
Elements: 1 2 3 4 5
Example 3:
Let us take another example to illustrate the Array.AsReadOnly(T) method in C#.
using System;
using System.Collections.Generic;
public class Program
{
// Main Method
public static void Main()
{
// Creating and initializing a new string array
string[] daysOfWeek = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
// Display the values of the daysOfWeek array
Console.WriteLine("Initial Array:");
// Calling the PrintArrayElements method to print
PrintArrayElements(daysOfWeek);
// Create a read-only IList wrapper around the array
IList<string> readOnlyDaysOfWeek = Array.AsReadOnly(daysOfWeek);
// Display the values of the read-only readOnlyDaysOfWeek
Console.WriteLine("\nRead-only Array:");
// Calling the PrintReadOnlyArrayElements method to print
PrintReadOnlyArrayElements(readOnlyDaysOfWeek);
}
// Method to print elements of a string array
public static void PrintArrayElements(string[] array)
{
foreach (string element in array)
{
Console.WriteLine(element);
}
}
// Method to print elements of a read-only string array
public static void PrintReadOnlyArrayElements(IList<string> readOnlyArray)
{
foreach (string element in readOnlyArray)
{
Console.WriteLine(element);
}
}
}
Output:
Initial Array:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Read-only Array:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Conclusion:
In conclusion, Array.AsReadOnly(T) is a useful method to create a read-only wrapper around an existing array in C#. Using this technique, developers can obtain an immutable view of the array's elements without making a duplicate of the original array. Its elements cannot be changed, safeguarding data integrity, and preventing accidental modifications because the array generates a read-only wrapper. As it implements IList and ICollection interfaces, the resulting read-only collection is compatible with methods and algorithms that require them. This method increases code safety and efficiency by providing an easy way to access array elements in a controlled and immutable manner. Array.AsReadOnly(T) is a vital tool for managing and interacting with arrays in C# applications.