0

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;
    }
}
1
  • 3
    What about it? The int array isn't immutable, just readonly, which means it just can be assigned once (barring some magic tricks like reflection). Its contents, on the other hand, can change... Commented Jun 19, 2013 at 8:56

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.