MikaAK
MikaAK

Reputation: 2364

How to edit a variable in a class array

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!

Upvotes: 2

Views: 202

Answers (6)

Paddyd
Paddyd

Reputation: 1870

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;

Upvotes: 0

sloth
sloth

Reputation: 101042

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).

Upvotes: 0

Artless
Artless

Reputation: 4568

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;

Upvotes: 0

aquaraga
aquaraga

Reputation: 4168

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

Upvotes: 0

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

You have to create the item(s) first

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

PS you should make those public members properties.

Upvotes: 0

Maxim Zhukov
Maxim Zhukov

Reputation: 10140

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

Upvotes: 3

Related Questions