Search code examples
c#.netreadonlyreadonly-collection

update Readonly int array?


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;
    }
}

Solution

  • 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 = new int[3];
    }
    

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

    Hope this helps.