Spiderbird
Spiderbird

Reputation: 87

C# - Declaring multiple arrays at the same time

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.

Upvotes: 2

Views: 4423

Answers (3)

Josh Withee
Josh Withee

Reputation: 11386

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

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

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.

Upvotes: 3

Gilad Green
Gilad Green

Reputation: 37281

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.

Upvotes: 8

Related Questions