473,473 Members | 1,854 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

C# Question: Iteration variable in a foreach() loop not always read only?

2 New Member
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:
Expand|Select|Wrap|Line Numbers
  1. int[] pins = {9, 3, 7, 2}
  2. int newPin = 10;
  3. foreach(int pin in pins)
  4. {
  5.     pin = newPin;  //Will give an error because pin is a read-only copy...
  6. }
  7.  
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:
Expand|Select|Wrap|Line Numbers
  1. DataTable dt = new DataTable();
  2. dt.Columns.Add("ID");
  3. dt.Columns.Add("Name");
  4. dt.Columns.Add("Msg");
  5. //code to fill dt
  6. foreach(DataRow dr in dt.Rows)
  7. {
  8.     string evaluationVariable, errorMsg;
  9.     //Code to populate the evaluationVariable and errorMsg
  10.     if (evaluationVariable == "Error")
  11.     {
  12.         dr["Msg"] = errorMsg;  //No error...but isn't dr["Msg"] read-only?
  13.     }
  14.     else
  15.     {
  16.         dr["Msg"] = "";  //No error...but isn't dr["Msg"] read-only?
  17.     }
  18. }
  19.  
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
Sep 28 '08 #1
1 3337
Shashi Sadasivan
1,435 Recognized Expert Top Contributor
Well, i found that out while i was programming, and have an explanation of that from my understanding.
However can you quote the exact words of that statement from the book ?

when you do a for loop over int or primitive data, a copy of the data is made only for the for loop element, and the compiler is smart enough to stop compiling, to alert that the element will not change the same element in the array.

However with the datarow example, the looping element is a reference of the array element. and any change made to the element will reflect in the array element as they both point to the same location.

Hope this makes some sense.
Sep 28 '08 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Vasileios Zografos | last post by:
Ok, easy question. Not caring about the variable scope what is better (i.e. possibly in memory allocation etc) int someVar=0; for (int i=0;i<1000;i++) { ...
1
by: siliconwafer | last post by:
Hi All, here is one code: int main() { FILE*fp; unsigned long a; fp = fopen("my_file.txt","w+"); a = 24; fprintf(fp,"%ld",a); while(fscanf(fp,"%ld",&a) == 1) {
3
by: cody | last post by:
why foreach does always have to declare a new variable? I have to write foreach (int n in array){} but Iam not allowed to write: int n=0; foreach (n in array){}
7
by: billr | last post by:
but ireally does need clearing up ... Traditionally (i.e. in C++) I might do the following: SomeObj ptrSomeObj; for(int i = 0; i < iCount; ++i) { ptrSomeObj = new SomeObj();...
15
by: MuZZy | last post by:
Hi, Consider this: ArrayList al = new ArrayList(); FillList(al); /// NOW TWO SCENARIOS: /// 1. for (int i = 0 ; i < al.Count ; i++)
8
by: SM | last post by:
I've always wonder if there is diference when declaring and initializing a varible inside/outside a loop. What's a better practice? Declaring and initializing variables inside a loop routine,...
4
by: bg_ie | last post by:
Hi, What is wrong with the following - short arrfile = new short; foreach (short s in arrfile) { s = 10; }
9
by: news.microsoft.com | last post by:
I am looping through an iteration and I would like to test the next item but if its not the one that I want how do I put it back so that when my foreach continues it is in the next iteration? ...
11
by: SM | last post by:
I have a couple of arrays that represent different categories. One array per category. The arrays contain names of photos. The arrays look like this: $cat_1 = array('moonlight.jpg'',...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.