Java Nerd
Java Nerd

Reputation: 968

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!

Upvotes: 0

Views: 972

Answers (2)

nvoigt
nvoigt

Reputation: 77354

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);
}

Upvotes: 0

Mohamed
Mohamed

Reputation: 520

If you just change the code

if (rec_part == rec.Length)
    rec_part = 0;
else
    rec_part += 1; 

It will work. But could you elaborate what excatly that you want to do?

Upvotes: 0

Related Questions