Why is a foreach loop a read only loop? What reasons are there for this?
Why is a foreach loop a read only loop? What reasons are there for
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I’m not sure exactly what you mean by a “readonly loop” but I’m guessing that you want to know why this doesn’t compile:
The above code will give the following compile error:
Why is this disallowed? Trying to assigning to it probably wouldn’t do what you want – it wouldn’t modify the contents of the original collection. This is because the variable x is not a reference to the elements in the list – it is a copy. To avoid people writing buggy code, the compiler disallows this.