Is it possible to make one array read-only. so the setpoint for the array will not be allowed.
this is what i tried with the readonly keyword to declare an array. Then I check if this array is read-only using the IsReadOnly property. but he never returns.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PrivateExposeConsoleApp
{
class Program
{
private static readonly int[] arr = new int[3] { 1,2,3 };
static void Main(string[] args)
{
IList<int> myList = Array.AsReadOnly(arr);
try
{
arr[2] = 100;
Console.WriteLine("Array Elements");
foreach (int i in arr)
{
Console.WriteLine("{0} - {1}", i + "->", i);
}
Console.WriteLine("---------------");
Console.WriteLine("List Elements");
foreach (int j in myList)
{
Console.WriteLine("{0} - {1}", j + "->", j);
}
myList[3] = 50;
}
catch (NotSupportedException e)
{
Console.WriteLine("{0} - {1}", e.GetType(), e.Message);
Console.WriteLine();
}
Console.ReadKey();
}
}
}
Here are my comments. if I uncomment this, my arr will never be read-only. upon declaration, I explicitly defined arr as readonly with data as {1,2,3}. I do not want this value to be rewritten. it should always be only 1,2,3.
source
share