Could someone please advise me if this is possible. I am looking at a code sample from Microsoft on GameState for their XNA framework. In one of the classes they use ‘Public ReadOnly’ array data members. Although not a practice that promotes OO but nothing wrong with that.
The class later instantiates it inside the constructor, so far so good, its documented on MSDN too.
PROBLEM: The class later iterates through the array in a class method and changes the data in the array. I looked on MSDN and Googled on it and everywhere I look it says flat out that will error out. Is there a special exception for read-only arrays?
Please advise.
public class InputState
{
public readonly KeyboardState[] CurrentKeyboardStates;
public readonly KeyboardState[] LastKeyboardStates;
public InputState()
{
CurrentKeyboardStates = new KeyboardState[max];
LastKeyboardStates = new KeyboardState[max];
}
//Does not make sense code...
public void Update()
{
for (int i=0; i < max; ++i)
{
//this should throw errors...
CurrentKeyboardStates[i] = LastKeyboardStates[i];
LastKeyboardStates[i] = Keyboard.GetState();
//more code....
}
}
}
Changing elements of a read-only array is perfectly fine, you just cannot re-assign the reference. (cannot set CurrentKeyboardStates/LastKeyboardStates to a new array, etc.) The element values can be changed.