# [windows forms: c++] arrays



## galmarsh (Apr 8, 2008)

whenever i try to use arrays with functions i get the following error at runtime.

"System.NullReferenceException: Objektreferensen har inte angetts till en instans av ett objekt."

in english: "System.Nullreferce exception, object reference hasnt been given to an instance of an object..."

for example below, im using rectangles and intersect/intersectsWith methods to find collisions, when moving controls.

first i make a rectangle object for each control. which i use to check for collisions.

private: System::Void form1_Load(System::Object^ sender, System::EventArgs^ e) {
Rectangle^ window = gcnew Rectangle(0,0,Form::Width,Form::Height);
Rectangle^ ball = gcnew Rectangle(ballC->Left,ballC->Top,ballC->Left+ballC->Width,ballC->Top+ballC->Height);
Rectangle^ b1 = gcnew Rectangle(bn1->Left,bn1->Top,bn1->Left+bn1->Width,bn1->Top+bn1->Height);
Rectangle^ b2 = gcnew Rectangle(bn2->Left,bn2->Top,bn2->Left+bn2->Width,bn2->Top+bn2->Height); 
Rectangle^ b3 = gcnew Rectangle(bn3->Left,bn3->Top,bn3->Left+bn3->Width,bn3->Top+bn3->Height);
Rectangle^ b4 = gcnew Rectangle(bn4->Left,bn4->Top,bn4->Left+bn4->Width,bn4->Top+bn4->Height);
Rectangle^ b5 = gcnew Rectangle(bn5->Left,bn5->Top,bn5->Left+bn5->Width,bn5->Top+bn5->Height);
collisionable = gcnew array<Rectangle^>{window,b1,b2,b3,b4,b5};
timer->Start();
}
private: System::Void timer_Tick(System::Object^ sender, System::EventArgs^ e) 
{
int check = collisionCheck(collisionable,ball);
if(check==-1)
{
//move actual control
ballC->Left += velX;
ballC->Top -= velY; // *NOTE* positive velY goes up.

//update rectangle too.
ball = Rectangle(ballC->Left,ballC->Top,ballC->Left+ballC->Width,ballC->Top+ballC->Height);
}
else
{
System::Array::Clear(collisionable,check,1);// remove brick if it was a brick....
}
}

***

protected:
Rectangle^ window, ball, b1, b2, b3, b4, b5;
array<Rectangle^>^ collisionable;

//check for collision between collisionObject and all elements of Rectangle array
// return -1 for no collision, else array's element id.
int collisionCheck(array<Rectangle^>^ arrayToCheck, Rectangle collisionObject)
{
int i=0, MAX = arrayToCheck->Length;
while(i<MAX)
{
if(arrayToCheck_->IntersectsWith(collisionObject))return i;
i++;
}
return -1; //no collisions
}
};
}

if you need any more specific details dont hesitate to ask, thanks._


----------



## galmarsh (Apr 8, 2008)

bump


----------

