Reputation: 11
I have this jagged array in C#:
private static readonly float[][] Numbers = {
new float[]{ 0.3f, 0.4f, 0.5}};
How can I override the value?
public static void SetNewNumbers(float[][] num){
Numbers = num;}
This is not working because of readonly,what should be added? ( I cant change anything about Numbers)
Upvotes: 1
Views: 1330
Reputation: 26907
You can reassign each value in Numbers
assuming the new array matches:
void ResetNumbers(float[][] num) {
if (num.Length != Numbers.Length || num[0].Length != Numbers[0].Length)
throw new ArgumentException($"{nameof(num)} dimensions incorrect");
for (int j1 = 0; j1 < Numbers.Length; ++j1) {
for (int j2 = 0; j2 < Numbers[j1].Length; ++j2) {
Numbers[j1][j2] = num[j1][j2];
}
}
}
Upvotes: 1
Reputation: 48258
here is the info you need:
In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.
when you declare Numbers
read only then this is not allowed
Numbers = num
coz you can not change the reference but you can modify the object...
so this is valid:
Numbers[0] = new[] {0.0f, 0.0f, 0.0f};
Numbers[0][1] = 1.0f;
Upvotes: 2