Search code examples
c#declare

Declare Instance of Class with Dynamic Name


So I have created a Class called SnakeItem, I want to create a new instance of the snake item when the snake grows, they follow a naming convention of snake_Piece_[NUMBER]. There is already snake_Piece_0 and I want to declare a new instance in the code. I'm not sure how to put it...

SnakeItem snake_Piece_0;
public game_Window()
{
    InitializeComponent();
    snake_Piece_0 = new SnakeItem(Resource1.Black, 0, 0);
}

Then in this function, I want to create it. (after snake_length++:) I need to name to increment so it follows the snake_length Variable. i.e. if snake_length = 1 then it will create a piece with the name snake_Piece_1.

 private void fruit_Collision()
 {
    if (snake_Piece_0.Top == Fruit_Item.Top && snake_Piece_0.Left == Fruit_Item.Left)
    {
       snake_Length++;
    }
  }

I'm not sure what I can say if it's not possible I would have to declare all 400 snake pieces beforehand which is what I'm trying to avoid.


Solution

  • This is a common thing that beginners do - trying to dynamically create new variables with new names. I tried to do this too, until I learned about Lists.

    Lists are objects that can store a variable number of objects. Here is how you can create an empty list of SnakeItem:

    List<SnakeItem> snakeItems = new List<SnakeItem>();
    

    You can add, access, and delete items in the list. Here are some examples:

    snakeItems.Add(new SnakeItem(Resource1.Black, 0, 0)); // add a new item to the list
    snakeItems[0] // access the first item in the list. 0 is the first, 1 is the second, etc.
    snakeItems.RemoveAt(0) // remove the first item of the list
    

    Basically, whenever you want to create a new "variable name", just Add a new item to the list:

        if (snakeItems[0].Top == Fruit_Item.Top && snakeItems[0].Left == Fruit_Item.Left)
        {
            snakeItems.Add(...);
        }
    

    As you can see, snake_Length is not needed any more! You can access how many snake items there are using .Count. Replace all the snake_Length with snakeItems.Count.

    Learn more about lists here.