CSharp · Console
// C# Extension Method
// Doc: https://csharp-extension.com/en/method/1002632/array-asreadonly
// @nuget: Z.ExtensionMethods
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
String[] myArr = { "The", "quick", "brown", "fox" };
Console.WriteLine("The string array initially contains the following values:");
PrintIndexAndValues(myArr);
// Create a read-only IList wrapper around the array.
// C# Extension Method: Array - AsReadOnly
IList<String> myList = myArr.AsReadOnly();
Console.WriteLine("The read-only IList contains the following values:");
PrintIndexAndValues(myList);
try
{
myList[3] = "CAT";
}
catch (NotSupportedException e)
{
Console.WriteLine("{0} - {1}", e.GetType(), e.Message);
Console.WriteLine();
}
myArr[2] = "RED";
Console.WriteLine("After changing the third element, the string array contains the following values:");
PrintIndexAndValues(myArr);
Console.WriteLine("After changing the third element, the read-only IList contains the following values:");
PrintIndexAndValues(myList);
}
public static void PrintIndexAndValues(String[] myArr)
{
for (int i = 0; i < myArr.Length; i++)
{
Console.WriteLine(" [{0}] : {1}", i, myArr[i]);
}
Console.WriteLine();
}
public static void PrintIndexAndValues(IList<String> myList)
{
for (int i = 0; i < myList.Count; i++)
{
Console.WriteLine(" [{0}] : {1}", i, myList[i]);
}
Console.WriteLine();
}
}