954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

passing by ref in foreach

I'm having problems with a passing a referance in a foreach loop.

"Cannot pass 'currentphoto' as a ref or out argument because it is a 'foreach iteration variable'"

foreach(photo currentphoto in thephotos){
panel1.Controls.Add(new thumbnailPicture(ref currentphoto));
}

I'm 100% sure that passing by referance would be the right way to elegantly deal with this. I need to basically expand this list into a panel which displays slots for each photo. Users can then drag photos into the slots.

Each slot holds a referance to a photo. So when users update a slot I want to change the details for the photo in the list. Then if the user does something else I can just dispose or clear the panel

The problem seems to be just the fact that it's in a foreach loop.

(I have tried turning it into a while loop and using ref thephotos[x] and that gives the same error but complaining that it's an array value instead)

Thanks in advance

Chris

jonesc5
Newbie Poster
18 posts since Oct 2007
Reputation Points: 8
Solved Threads: 0
 

sorted it by trial and error
easy really

foreach(photo currentphoto in thephotos){
                    photo tempphoto = currentphoto;
                    panel1.Controls.Add(new thumbnailPicture(ref tempphoto));
            }


if there is a better way of doing this feel free to tell me. This seems like one of thoose annoying fixes as i'm not sure why it works. It will probably bite me later.

jonesc5
Newbie Poster
18 posts since Oct 2007
Reputation Points: 8
Solved Threads: 0
 

It's C# compiler restriction Cannot pass 'currentphoto' as a ref or out argument because it is a 'foreach iteration variable' and your solution is good to avoid this restriction.

Ramy Mahrous
Postaholic
2,196 posts since Aug 2006
Reputation Points: 480
Solved Threads: 276
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You