Reputation: 83
I am currently creating a program where the user can use a printer as long as that particular user has enough funds.
The current issue I am having is that if the user chooses to have colour printing instead of black and white then the price for each piece of paper goes up.
How do I add value to an already existing array?
Here is my code...
printers[0] = new Printer("printer1", 0.10M);
printers[1] = new Printer("printer2", 0.08M);
printers[2] = new Printer("printer3", 0.05M);
printers[3] = new Printer("printer4", 0.15);
printers[4] = new Printer("printer5", 0.09M);
foreach (Printer r in mPrinters)
{
if (printer != null)
printerCombo.Items.Add(r.getName());
}
Upvotes: 0
Views: 110
Reputation: 186688
Technically, you can Resize the array:
Array.Resize(ref printers, printers.Length + 1);
printers[printers.Length - 1] = new Printer("printer6", 0.25M);
However, a much better approach is to change the collection type: array into List<T>
:
List<Printer> printers = new List<Printer>() {
new Printer("printer1", 0.10M),
new Printer("printer2", 0.08M),
new Printer("printer3", 0.05M),
new Printer("printer4", 0.15),
new Printer("printer5", 0.09M), };
...
printers.Add(new Printer("printer6", 0.25M));
Upvotes: 3
Reputation: 12171
Arrays have fixed size - after you created array with size 10 you can't add one more element (to make size 11).
Use List<Printer>
:
List<Printer> printers = new List<Printer>();
printers.Add(new Printer("printer2", 0.08M));
//add all items
Also you can access elements by index:
var element = printers[0];
Using List
you can change its size, add and remove elements.
Upvotes: 1
Reputation: 6520
Arrays are fixed length. You need to copy the values into a new array or use an List, List<>, or ArraryList.
Upvotes: 0