C# Adding to an Array

I have this problem in C# where when I try to add an item to an array, it simply makes the array blank. No error is produced.

My code for adding an item:

public void AddItem ( string itemName  ,   int qty ,   string type  ){
	Item itemToAdd = new Item();
	itemToAdd.name = itemName;
	itemToAdd.quantity = qty;
	itemToAdd.type = type;
	ArrayList itemsResizeableArray = new ArrayList();
	if ( items != null && items.Length != 0 )
		itemsResizeableArray = new ArrayList( items );
	itemsResizeableArray.Add( itemToAdd );
	items = itemsResizeableArray.ToArray() as Item[];

I would rather not use Lists because I would need to change a large portion of my Unity Project. I create the Array here:

public Item[] items;

and declare the class:

public class Item
	public string name = "";
	public int quantity = 1;
	public string type = "";

I would like help making my function actually add an Item to the array.

Thanks in advance.

ArrayList.ToArray() returns object[]. You can’t cast it to Item[], so using ‘as’ keyword causes items to be null again. To be able to accomplish this, you can change your line to:

items = itemsResizeableArray.ToArray(typeof(Item)) as Item[];

But, please DON’T do this, and instead change your variable definition to

public List<Item> items;

as @Eric5h5 suggested. With this change, instead of calling AddItem(“x”, 1, “y”), you can simply do

items.Add(new Item
    name = "x",
    quantity = 1,
    type = "y"

or you can add proper constructor to your Item class, and just call

items.Add(new Item("x", 1, "y"));

You’d need to modify your code of course, but I strongly suggest doing it. Even if you use this variable in 100 lines, most of them won’t require any change, and you can fix all in a matter of minutes.