In Classical sense Readonly objects can only be set in the constrcutor and cannot be modified later on. Why do readonly int arrays behave any different.

PS:I am aware of Readonly collections, I am just curious to know why is this allowed ?

class Class1
{
    public readonly int[] a;

    public Class1()
    {
        a = new int[3];
        a[0] = 1;
        a[1] = 2;
        a[2] = 3;
    }

    public void Update()
    {
        a[0] = 10;
    }
}
有帮助吗?

解决方案

Readonly modifier is applied to actual type it assigned to. So in this case it assigned to an Array type instance, but not to a elements present inside it.

That's why, yes, you still able to change element value, but the code like

public void Update()
{
   a[0] = new int[3];
}

will fail, as you're going to change Array type instance (and not its content)

Hope this helps.

其他提示

readonly makes the array immutable, not the array items. readonly means you can assign an array to an a field inline or in constructor only. But it does not prevent anyone to change the content of each array item.

If you make this array content to be readonly do like this

public readonly int[] a;
ReadOnlyCollection<int> result = Array.AsReadOnly(a);
public Class1()
{
    a = new int[3];
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;

}

public void Update()
{
    result[0] = 10; // Compile Time Error Here
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top