문제

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