Search code examples
c#arraysgraphicsdrawrectangle

Rectangle not drawing using array


Hye there I am new to c# and need to draw rectangle using an array. My code is:

        Rectangle[] rec;
        int rec_part=2;

        public Form1()
        {
            InitializeComponent();
            rec = new Rectangle[rec_part];

            for (int i = 0; i <rec_part; i++)
            {
                rec[i] = new Rectangle(10, 100, 40,40);
            }
        }

so my code draws only one Rectangle at the time:

        Graphics g;
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
             g = e.Graphics;

            for (int i = 0; i<(rec_part);  i++)
            {

                g.FillRectangle(new SolidBrush(Color.Blue), rec[i]);  //exception here

            }
        }

the thing is I want to move my Rectangle and at the same time I want to increment the Rectangle Array Length! i.e.

        int speed = 2;
        private void timer1_Tick(object sender, EventArgs e)
        {

            for (int i = 0; i < rec.Length; i++)
            {

                rec[i].X += speed;
                rec_part+=1;          // here i want to increment the rectangles
                this.Refresh();
            }


        }

My objective is to increment the number of rectangles once timer starts working. But I am getting Exception of Index out of Bounds! Can somebody give any idea or suggestion how can i do that please! Thanks in advance!


Solution

  • You cannot add elements to an array. Use a list:

    private List<Rectangle> rectangleList = new List<Rectangle>();
    

    Then you can add as many rectangles as you like:

    rectangleList.Add(new Rectangle(10, 100, 40,40));
    

    In C#, you can use a foreach-loop instead of the for loop:

    foreach(var r in rectangleList)
    {
       g.FillRectangle(new SolidBrush(Color.Blue), r);
    }