Array.AsReadOnly(T[]) Method in C#

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:

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#.

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#.

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#.

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.






Latest Courses