Reputation: 31
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.
Upvotes: 3
Views: 8900
Reputation: 770
I hope the following is what you are expecting. I modified the code for you.
// 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
string[] tabletPricesArray = new string[]{"$1,162.99",
"$399.99",
"$329.99",
"$199.99",
"$149.99"};
Upvotes: 4
Reputation: 20794
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.
Upvotes: 6