Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidCastException on Result of Indexing Into an ArrayList

I have an ArrayList filled with a bunch of Points and I want to loop over them, so I use this code:

for (int i = 0; i < currentClicks.Count; i++)
{
    if (i > 0) // Skip the first click
    {
        clickPos = currentClicks[i];
        prevPos = currentClicks[i - 1];
    }
}

and I get this error on the clickPos and prevPos lines:

Cannot implicitly convert type 'object' to 'System.Drawing.Point'.
An explicit conversion exists (are you missing a cast?)

Why is this? I have clickPos and prevPos defined as so:

private System.Drawing.Point clickPos;
private System.Drawing.Point prevPos;

Edit

When I comment out the clickPos and prevPos lines and add

MessageBox.Show(currentClicks[i].GetType().ToString());

the message box says System.Drawing.Point

like image 313
RyanScottLewis Avatar asked Dec 05 '22 03:12

RyanScottLewis


2 Answers

Try this:

for (int i = 1; i < currentClicks.Count; i++)
{
    clickPos = (System.Drawing.Point)currentClicks[i];
    prevPos = (System.Drawing.Point)currentClicks[i - 1];
}

A better solution could be using a generic list, a List<Point>, then you wouldn't need the cast at all.

like image 35
Nick Craver Avatar answered Feb 23 '23 20:02

Nick Craver


You should use the generic List<Point> instead of an ArrayList.

If you insist on using an ArrayList, you'll need to cast the objects to a Point when you retrieve them:

clickPos = (Point)currentClicks[i];
like image 152
Anon. Avatar answered Feb 23 '23 21:02

Anon.