|
-
Aug 5th, 2007, 10:47 PM
#1
Thread Starter
Hyperactive Member
[RESOLVED] How do you cycle through an array of objects?
Code:
foreach (Room q in rooms)
{
rooms[q].rWall = "|";
rooms[q].floorDwn = "_";
}
When I try Room I get the error:
Cannot implicitly convert type 'MazeGen.Room' to 'int'
And when I try int q in rooms I get the error:
Cannot convert type 'MazeGen.Room' to 'int'
Thank you in advance for showing me how to cycle through the index of an array.
I have seen it to be done like this:
foreach (char ch in str)
but I'm not able to resemble it in this case.
-
Aug 5th, 2007, 10:51 PM
#2
Re: How do you cycle through an array of objects?
The whole point of a foreach loop is that the loop counter IS the item from the list. Youre' treating it like a for loop, where the loop counter is an index that you use to get the item. As this part says:
Code:
foreach (Room q in rooms)
the q variable IS the Room object, not an index into the array to get a Room object. Your code should be:
C# Code:
foreach (Room q in rooms)
{
q.rWall = "|";
q.floorDwn = "_";
}
-
Aug 5th, 2007, 11:14 PM
#3
Thread Starter
Hyperactive Member
Re: How do you cycle through an array of objects?
I tried to do as you have written but I am getting the error:
Cannot modify members of 'q' because it is a 'foreach iteration variable'
-
Aug 6th, 2007, 12:54 AM
#4
Re: How do you cycle through an array of objects?
Can you show us the type definition for Room?
-
Aug 6th, 2007, 04:08 AM
#5
Re: How do you cycle through an array of objects?
OK, I just did some testing of my own and it seems that you can set fields/properties of reference types, i.e. classes, in a foreach loop like that but you can't do so with value types, i.e. structures. Thus I assume that your Room type is a structure.
This is explained by the fact that in your code q will be a copy of the actual value in the array, so setting its fields/properties is pointless because it will not affect the original. If you want to change fields/properties of an array of structures then use a for loop instead of a foreach loop:
-
Aug 6th, 2007, 11:46 AM
#6
Thread Starter
Hyperactive Member
Re: How do you cycle through an array of objects?
You are right. It is an array of structures.
I didn't realize this before but your explanation was very helpful.
Thanks so much.
-
Aug 7th, 2007, 08:02 AM
#7
Re: [RESOLVED] How do you cycle through an array of objects?
You shouldn't use structures unless its absolutely essential that they have value type semantics. Reference types are superior in most situations.
-
Aug 7th, 2007, 05:46 PM
#8
Thread Starter
Hyperactive Member
Re: [RESOLVED] How do you cycle through an array of objects?
Thank you for that advice.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|