Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can array initializers only be used in a variable or field initializer?

Tags:

c#

I'm getting the following error:

Array initializers can only be used in a variable or field initializer. Try using a new expression instead.

Here is my code:

// Declare listbox information array
string [] tablet = new string[]{{"Microsoft Surface  Price: $1,162.99  Screen Size: 10.6 Inches  Storage Capacity: 128 GB"},

                                {"iPad 2 Price: $399.99, Screen Size: 9.7 Inches, Storage Capacity 16 GB"},
                                {"Samsung Galaxy Tab 2 Price: $329.99, Screen Size: 10.1 Inches, Storage Capacity 16 GB"},
                                {"NOOK HD Price: $199.99, Screen Size: 7 Inches, Storage Capacity 8 GB"},
                                {"IdeaTab Price: $149.99, Screen Size: 7 Inches, Storage Capacity: 8 GB"}};

//Array of product prices
int [] tabletPricesArray = new int[]{{"$1,162.99"},
                                       {"$399.99"},
                                       {"$329.99"},
                                       {"$199.99"},
                                       {"$149.99"}};

I am not really sure what is going wrong. I'm relatively new to C#. Let me know if any additional information is needed.

like image 816
Simon Kay Avatar asked Aug 13 '26 02:08

Simon Kay


1 Answers

A couple of issues:

Problem 1:

Here you are creating an array of type int while providing strings.

  int [] tabletPricesArray = new int[]{"$1,162.99",
                                         "$399.99",
                                         "$329.99",
                                         "$199.99",
                                         "$149.99"};

Problem 2:

An array of type int will not hold floating point values such as prices. Instead use float, double, or decimal (for $).

    decimal[] tabletPricesArray = new decimal[]{1162.99M,
                                                 399.99M,
                                                 329.99M,
                                                 199.99M,
                                                 149.99M};

If you want tabletPricesArray to only be used for displaying items as strings (no calculations), then you can use the string array here as well.

Problem 3:

You don't need { } in each array element.

like image 154
Inisheer Avatar answered Aug 15 '26 19:08

Inisheer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!