1

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)

7
  • 4
    That is the point of readonly, so you can't assign new value to it. Commented Feb 12, 2021 at 9:56
  • If num has the same number of outermost elements as Numbers, you're OK (i.e. 1 element, in your example). Otherwise, you're out of luck: that's the point of readonly Commented Feb 12, 2021 at 9:56
  • But in case if outer arrays have the same number of inner ones you can just reassign them one by one. Commented Feb 12, 2021 at 9:57
  • Thank you for answers. Yes, they are the same, just different float values. I cant change anything about Numbers. What I need is: If a certain criteria is met I want to override this values, but if later the criteria is not met anymore, I want to return to the default values set in Numbers Commented Feb 12, 2021 at 10:06
  • 3
    It's readonly, therefore you can only assign it when you initialize it or in the constructor. If you want to change the values later, you should not make it readonly. What was the reason you put readonly there to begin with? Edit: You want if certain criteria is met, to go back to the default. In this case, maybe make two variables? One readonly which is the default, and another one which actually holds the current value, which is not readonly? Commented Feb 12, 2021 at 10:13

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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];
        }
    }
}

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.