3

I am trying to remove an object from an array and fill the slot with an object of the same type but with 0s for all the properties. But when I do this the values do not clear for some reason when I recalculate the array values.

Here is how I am clearing an object out and inserting a blank one in its place.

    public void clearOutBox(int arraySlot)
    {
        itemsInbuildArray.Remove(itemsArray[arraySlot]);
        itemsInbuildArray.Insert(arraySlot, blank);
        itemInBuildPictureArray[arraySlot].ImageLocation = null;
        statCalculation();
    }

    //one of the lines from the statCalculation method. 
    statsHealth.Text = (Convert.ToString(itemsInbuildArray.Sum(hp => hp.Health)));

        public partial class Form1 : Form
{
    List<Item> itemsArray = new List<Item>();
    List<PictureBox> itemInBuildPictureArray = new List<PictureBox>();
    List<ToolTip> itemInBuildTooltipArray = new List<ToolTip>();
    List<Item> itemsInbuildArray = new List<Item>();
            Item blank = new Item(); // this is one of several objects created here
}

I initialize the array with 6 of these blank items in it and there are no problems replacing a blank item with one with values but removing it is whats causing me issues.

Please excuse the more than likely noobish ways I'm doing this, I am just starting C# and doing this project as a learning experience. Any input is appreciated!

3
  • 2
    Why not just itemsInbuildArray[arraySlot] = blank? Commented Jul 25, 2011 at 21:43
  • Where is this "blank" object coming from (line #4 in your code) and how do you create it? Commented Jul 25, 2011 at 21:45
  • You need to give a bit more information - you appear to have 3 array like objects - at least one of which itemsInbuildArray is actually an ArrayList not an Array. Commented Jul 25, 2011 at 21:52

1 Answer 1

2

Why not just index it directly:

int index = 5;
array[index] = new Foobar(); // whatever your class is

That is going to change whatever is referenced in the 6th slot in your array.

I would avoid using a single reference called "blank" and putting it into multiple array slots unless you know you will never modify them. If they are reference types then modifying one of them would modify them all.

Sign up to request clarification or add additional context in comments.

2 Comments

blank is just the name of an object. They all have to be blank initially because the values are calculated as each item is entered and if there is not something in there it crashes
This solved my problem! I guess I was just over complicating it thank you.

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.