Okay, I'll caveat this question with two things. One, I'm not as smart as you (I'm really not). Second, I may have found an answer to my own question, but want to verify.
I'm attempting to declare multiple arrays at the same time. It looks something like this. The first is just declaring a single array, while the second tries to declare both profit_Normal and profit_High in the same line:
double [] tradeType_Active = new double [15];
double [] profit_Normal, profit_High = new double [5];
Can I do this? I currently use this syntax for declaring non-array values with commas, like this:
double
BUpper,
BUpper_Prev,
BUpper_Prev2;
Please let me know when you have a moment.
-
3Yes you can, it is perfectly valid. I must admit that this is more common for C, not very common to see someone to write it like this is C#, but it is valid.vasil oreshenski– vasil oreshenski2017年12月21日 18:22:06 +00:00Commented Dec 21, 2017 at 18:22
-
1If you want n new double arrays you need n new double assignments.Alex K.– Alex K.2017年12月21日 18:23:23 +00:00Commented Dec 21, 2017 at 18:23
-
Thanks you very much for the comments and validation. I also just realized, in a round-about way, that the title of my post inadvertently referenced a popular line from Office Space.Spiderbird– Spiderbird2017年12月21日 18:34:53 +00:00Commented Dec 21, 2017 at 18:34
3 Answers 3
Your line of code
double[] profit_Normal, profit_High = new double[5];
does declare multiple double[]. What it doesn't to is to initialize all of them. It initializes only the second one.
If you have the following line:
double[] a, b, c, d = new double[5];
what happens is that you are declaring 4 references of arrays of double. For each array you declare you must initialize it - which you are doing only for the last.
To initialize multiple arrays you need to actually initialize them:
double[] profit_Normal = new double[5], profit_High = new double[5];
The difference between the arrays case and this double BUpper, BUpper_Prev, BUpper_Prev2; is that arrays are reference types that their default value is null and must be initialized, whereas doulbe's default value is 0.
1 Comment
Yes, this is absolutely allowed, as long as you keep [] in the declaration to indicate that you are declaring an array:
double[] a = new double[4], b = new double[5];
The double[] part is the type of variables being declared. In your case, that's an array of double.
Note that the only difference between the above and your second declaration is that you did not initialize the profit_Normal variable.
1 Comment
You can use the same syntax you currently use, but in order to instantiate each one as well as declaring it, it would look like this, with = new double[5] after each one:
double[]
profit_Normal = new double[5],
profit_High = new double[5];