2

Not sure how to phrase title so sorry for poor wording but if I have something like this

public class Item
{ 
     public string itemName;
     public double itemPrice;
     public double shipping;
     public double tax = 0.12;
     public double total;
}

Then I proceeded to declare an array

Item[] item = new Item[100]

I feel like this is a bad way to create an array like this but the problem here is an arbitrary sized array so I know for sure it will be under 100 but the items will keep getting added on.

How can I now edit item[0]'s itemPrice?

I tried using:

item[0].itemPrice = 34;

but with no avail.

Thanks!

3
  • Have you initialized each of the item objects in the array? Commented Jul 25, 2013 at 8:58
  • On a side-note you might want to read up on how to use constructors and getter/setter methods. Commented Jul 25, 2013 at 9:00
  • If it helped you, you could accept the correct answer Commented Jul 25, 2013 at 9:12

6 Answers 6

3

When you use Item[] item = new Item[100];, you just allocate memory for your collection, but you need to initialize each object in this array too.

Item[] item = new Item[100];
item[0] = new Item();
item[0].itemName = "1";
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks i didn't initialize each item.
you will need a loop to initialize each item in the array.
0

You have to create the item(s) first

item[0] = new Item();
item[0].itemprice = 34;

PS you should make those public members properties.

Comments

0
var items = new List<Item>();
item.Add(new Item())
items.First().ItemName = "Foo";

Comments

0

Try using List<Item> instead of an array. List<T> automatically extends itself when you add items to it.

List<Item> list = new List<Item>();
Item myItem = new Item();
list.Add(myItem);

list[0].itemPrice = 0;

Comments

0

If you declare an array of Item, you're creating the array, but no class instances; item[0] will be null.

An easy way to create an arbitary number of instances is using Enumerable.Range:

var items = Enumerable.Range(0, 20).Select (_ => new Item()).ToList();

This creates a list of 20 Item instances (you could also create an array by calling ToArray instead of ToList).

Comments

0

You have to initialize each item in the array. Assuming you have a suitable constructor...

Item[] item = new Item[100]

for (int i = 0; i < 100; i++)
{
    item[i] = new item();
}

item[0].itemPrice = 34;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.