Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing array elements of a List<object[]> in foreach loop

Tags:

c#

object

foreach

This is what I have:

List<object[]> markers = new List<object[]>();

object[] marker = new object[2];
marker[0] = new Vector2(1, 2);
marker[1] = new Vector4(1, 2, 3, 4);
markers.Add(marker);

foreach (var item in markers)
{
    int x = (Vector2)item[0].X; // Error: 'object' does not contain a definition
                                // for 'X' and no extension method 'X' accepting
                                // a first argument of type 'object' could be
                                // found (are you missing a using directive or
                                // an assembly reference?)
    // other stuff
}

Is there a way to make this work without losing code readability, or should I try using a class instead of object array?

like image 209
user1306322 Avatar asked Jul 09 '12 18:07

user1306322


Video Answer


1 Answers

You need to do this (operator precedence issue)

((Vector2)item[0]).X;

However I don't think it is good practice to have different object types in the same array. That's why generic List has been introduced ( lack of type safety with ArrayList).

Your code is trying to do something like :

ArrayList vectors = new ArrayList { new Vector2(22, 33), new Vector4(223, 43, 444, 33}};

This was before .Net 2.0. And it was causing some problems.

like image 120
MBen Avatar answered Oct 13 '22 01:10

MBen