Hi,
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:
That makes sense to me, I can live with that. However, recently when I was working with a DataRow object, I found what appeared to be a contradiction to that rule. When I used a DataRow variable as an iteration variable, I was able to update a value in one of the columns in the DataRow. For example:
I'm sorry for the crudeness of the examples above, but I'm hoping that they get my point across. If not, let me know and I'll try to clarify.
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
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:
Code:
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...
}
Code:
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
Comment