I am a pretty new programmer, so I apologize in andvance if this is a dumb question...
In a book that I'm reading to learn C#, it says that when using a foreach() loop, a read-only copy of the iteration variable is used and you cannot modify it. For example:
Expand|Select|Wrap|Line Numbers
- int[] pins = {9, 3, 7, 2}
- int newPin = 10;
- foreach(int pin in pins)
- {
- pin = newPin; //Will give an error because pin is a read-only copy...
- }
Expand|Select|Wrap|Line Numbers
- DataTable dt = new DataTable();
- dt.Columns.Add("ID");
- dt.Columns.Add("Name");
- dt.Columns.Add("Msg");
- //code to fill dt
- foreach(DataRow dr in dt.Rows)
- {
- string evaluationVariable, errorMsg;
- //Code to populate the evaluationVariable and errorMsg
- if (evaluationVariable == "Error")
- {
- dr["Msg"] = errorMsg; //No error...but isn't dr["Msg"] read-only?
- }
- else
- {
- dr["Msg"] = ""; //No error...but isn't dr["Msg"] read-only?
- }
- }
Are there certain times, like when working with a DataRow that the iteration variable in a foreach() loop is not read only or am I missing something (a very real possibility)? It would seem that there are two different rules for a foreach() loop's iteration variable. I have looked and looked on Google for the answer to this and I have not been able to find an answer telling me why I am able to update a value in the DataRow column which is the iteration value in a foreach() loop. Could somebody please help out a beginner and show me what I'm missing?
Thanks for any help that you can give.
Regards,
John