-1

I have the below piece of code.

public class SimpleStack
{
    private readonly double[] _items;
    
    public void Push(double item)
    {
        _items[0] = item;
    }

}

How come I am able to mutate the readonly _items array and the compiler allows it ?

jhon.smith
  • 1,963
  • 6
  • 30
  • 56
  • 2
    I get the following when I run your snippet: Run-time exception (line 18): Object reference not set to an instance of an object. Line 18 points to _items[0] = item. – ddastrodd Dec 13 '22 at 03:29
  • 2
    `readonly double[]` doesn't means that its content is `readonly`. Consider the `double[]` as a pointer, the pointer itself is readonly (i.e., you cannot change where the pointer is pointing to), but the memory that it is pointing to can be changed. – imamangoo Dec 13 '22 at 03:30
  • Thanks a ton imamangoo and gunr2171 i was preplexed by that problem. – jhon.smith Dec 13 '22 at 03:36

1 Answers1

5

It’s the array that is read only, not the contents of the array. So you wouldn’t be able to overwrite the array itself after the constructor, but the contents are fair game.

Adam B
  • 3,662
  • 2
  • 24
  • 33