Array.Asreadonly(T[]) Method In C#

In this post, we are going to explore the Array.AsReadOnly(T) method in C# along with its syntax, parameters, and illustrations.

What is the Array.AsReadOnly__PRESERVE_7__(T) method?

This technique is employed to generate a read-only wrapper for the given array. The Array serves as a useful utility within the System, particularly in the.NET framework using C#. The AsReadOnly(T) method belongs to the collections.ObjectModel namespace. By utilizing this approach, it becomes possible to present an original array as a read-only wrapper, granting a fixed and unmodifiable perspective of the array's elements.

Syntax:

It has the following syntax:

Example

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 will raise an ArgumentNullException if the array is null.

Example 1:

Let's consider a scenario to demonstrate the Array.AsReadOnly(T) method in C#.

Example

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:

Output

Demonstrating LastIndexOf method...
Array elements:
car bike truck bus motorcycle 
Last occurrence of 'bus' is at index = 3

Example 2:

Let's consider a different instance to demonstrate the Array.AsReadOnly(T) method in the C# programming language.

Example

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:

Output

First element: 1
Elements: 1 2 3 4 5

Example 3:

Let's consider a different scenario to demonstrate the Array.AsReadOnly(T) method within the C# programming language.

Example

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:

Output

Initial Array:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Read-only Array:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Conclusion:

In summary, the Array.AsReadOnly(T) method in C# proves to be a valuable tool for encapsulating an existing array in a read-only wrapper. By utilizing this approach, programmers can access a non-modifiable perspective of the array's contents without duplicating the original array. This protective measure ensures the integrity of data by prohibiting any inadvertent alterations, as the array is enveloped within a read-only wrapper. Moreover, since it adheres to IList and ICollection interfaces, the resultant read-only collection seamlessly integrates with methods and algorithms that necessitate these interfaces. By enabling controlled and immutable access to array elements, this method enhances code reliability and efficiency. Array.AsReadOnly(T) emerges as an indispensable asset for effectively managing and interacting with arrays within C# applications.

Input Required

This code uses input(). Please provide values below: