Pregunta

is it possible to make one array readonly. such that set value to array will not be allowed.

here what i have tried with readonly keyword for declaring the array. Then i am checking if that array is readonly by using IsReadOnly property. but it never returns true.

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)
        {
            // Create a read-only IList wrapper around the array.
            IList<int> myList = Array.AsReadOnly(arr);

            try
            {
                // Attempt to change a value of array through the wrapper. 
                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);
                }
                // Attempt to change a value of list through the wrapper. 
                myList[3] = 50;
            }
            catch (NotSupportedException e)
            {

                Console.WriteLine("{0} - {1}", e.GetType(), e.Message);
                Console.WriteLine();
            }



            //if (arr.IsReadOnly)
            //{
            //    Console.WriteLine("array is readonly");
            //}
            //else
            //{
            //    for (int i = 0; i < arr.Length; i++)
            //    {
            //        arr[i] = i + 1;
            //    }

            //    foreach (int i in arr)
            //    {
            //        Console.WriteLine(i);
            //    }
            //}

            Console.ReadKey();
        }
    }
}

Here see my commented parts. if i uncomment this my arr never becomes readonly. at the declaration i explicitily defined arr as readonly with the data as {1,2,3}. i don't want this value to be rewitten . it should be always 1,2,3 only.

¿Fue útil?

Solución 2

The method Array.AsReadOnly<T>(T[] array) which is defined on the Array class itself is supposed to be used for this purpose.

The method takes an array as an argument (the one you want to make read-only) and returns a ReadOnlyCollection<T>.

An example would be as follows:

// declaration of a normal example array
string[] myArray = new string[] { "StackOverflow", "SuperUser", "MetaStackOverflow" };

// declaration of a new ReadOnlyCollection whose elements are of type string
// the string array is passed through the constructor
// that's is where our array is passed into its new casing
// as a matter of fact, the ReadOnlyCollection is a wrapper for ordinary collection classes such as arrays
ReadOnlyCollection<string> myReadOnlyCollection = new ReadOnlyCollection<string>(maArray);

Console.WriteLine(myReadOnlyCollection[0]); // would work fine since the collection is read-only
Console.WriteLine(myReadOnlyCollection[1]); // would work fine since the collection is read-only
Console.WriteLine(myReadOnlyCollection[2]); // would work fine since the collection is read-only

myReadOnlyCollection[0] = "ServerFault"; // the [] accessor is neither defined nor would it be allowed since the collection is read-only.

Here you can find the according MSDN documentation.


Alternatively you might simply define a getter-method such as

public T getElement(int index) { return array[index]; }

in order to make your array read-only - at least from outside its class?


Regarding your use of Array.IsReadOnly the MSDN documentation says that

This property is always false for all arrays.

That means you will have to use IList<T>.IsReadOnly instead of arr.IsReadOnly.

See here

Otros consejos

Arrays are inherently mutable and to get the behavior you want you need to use the wrapper, ReadOnlyCollection<T>. You can create a read only copy of the array using arr.AsReadOnly()

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top