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;
    }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Rauld
  • 980
  • 2
  • 10
  • 19
  • 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... – Patryk Ćwiek Jun 19 '13 at 08:56

3 Answers3

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.

prime23
  • 3,362
  • 2
  • 36
  • 52
Tigran
  • 61,654
  • 8
  • 86
  • 123
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.

tdragon
  • 3,209
  • 1
  • 16
  • 17
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
}
Rajeev Kumar
  • 4,901
  • 8
  • 48
  • 83