As you are instantiating a rectangle and then drawing it immediately, there doesn't seem any reason for your code to be actually storing an array of rectangles. The simple way for you to draw the rectangle there is to simply replace the inner part of your loop with:
g.DrawRectangle(myPen, new Rectangle(x+(j*offset), (y+i*offset), offset, offset));
Is there processing elsewhere that requires this list of rectangles, or is it sufficient that you are simply drawing it. BTW, by doing this you can get rid of the rectangle array declaration altogether.
[Edit]Following clarification from the OP as to what he was after:
I would separate the creation of the rectangle away from the drawing of the rectangle. One problem you currently face is that you are instantiating and populating the array in every
OnPaint
event. Instead, create it prior to drawing like this:
private List<Rectangle> rectangles = new List<Rectangle();
private void SetupRectangles(int m, int offset)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
rectangles.Add(new Rectangle(x+(j*offset), (y+i*offset), offset, offset));
}
}
}
Then in your
OnPaint
handler, all you need do is this:
if (rectangles.Count == 0)
{
SetupRectangles(m, offset);
}
foreach (Rectangle rect in rectangles)
{
g.DrawRectangle(myPen, rect);
}
It's as simple as that.