473,322 Members | 1,610 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

why foreach does always have to declare a new variable

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){}

what is the reasoning behind that?

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
Nov 16 '05 #1
3 3253

"cody" <pl*************************@gmx.de> wrote in message
news:uY**************@TK2MSFTNGP10.phx.gbl...
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){}

what is the reasoning behind that?


I don't have a definitive answer, but I can give some fairly good answers.

One thing is that it helps avoids silly mistakes like
string item;
.... //code that uses item
foreach(item in Items)
{
}

Also, since the variable is always assigned to, there is no value in
allowing pre-existing assignment.
int n = 0;
foreach (n in array)

will *never* use n as it is, instead assinging from the array, thus there is
no real reason to allow it.

And, finally, since foreach *does* result in a cast, defining the type
directly within the foreach statement makes code much clearer.
Nov 16 '05 #2
> > 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){}

what is the reasoning behind that?

I don't have a definitive answer, but I can give some fairly good answers.

One thing is that it helps avoids silly mistakes like
string item;
... //code that uses item
foreach(item in Items)
{
}

Also, since the variable is always assigned to, there is no value in
allowing pre-existing assignment.
int n = 0;
foreach (n in array)


That is right but the code was meant that the variable n could be used by
other code either before or after the loop in which case it would have to be
explicitly assigned to.
And, finally, since foreach *does* result in a cast, defining the type
directly within the foreach statement makes code much clearer.


Thinking about it this sounds very very reasonable :)

I've never liked the implicit cast in foreach loops because it is very
dangerous and once we have generics it will be very superflous too.

My proposal is that in csc 2.0 there should be an option that if foreach
loop variable would require an implicit cast, a warning is outputted.
Additionally, when using a generic IEnumerator in the foreach loop, the
warning is *always* outputted, no matter what the compiler settings are.
e.g

IList list = new ArrayList();
foreach (string s in list) // warning is outputted only if compilersetting
is set

IList<object> list = new ArrayList<object>();
foreach (string s in list) // a warning is always issued

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
Nov 16 '05 #3
>> Also, since the variable is always assigned to, there is no value in
allowing pre-existing assignment.
int n = 0;
foreach (n in array)


That is right but the code was meant that the variable n could be used by
other code either before or after the loop in which case it would have to
be
explicitly assigned to.


Yes, but its a waste, IMHO. It makes code more confusing, I would probably
consider any code using that pattern as fragile at best, badly written more
likely.
And, finally, since foreach *does* result in a cast, defining the type
directly within the foreach statement makes code much clearer.


Thinking about it this sounds very very reasonable :)

I've never liked the implicit cast in foreach loops because it is very
dangerous and once we have generics it will be very superflous too.

My proposal is that in csc 2.0 there should be an option that if foreach
loop variable would require an implicit cast, a warning is outputted.
Additionally, when using a generic IEnumerator in the foreach loop, the
warning is *always* outputted, no matter what the compiler settings are.


Yes, I know. And as I said the last time you suggested this, I think its
unimportant, especially since you're the first person I've seen complain
about it.

I really don't agree that the implicit cast is dangerous by any degree, its
only implicit if you a) don't know what you are doing, or b) allow code like
you recommend without the type specifier. The behaviour is sane and pretty
clear, IMHO.
Nov 16 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
by: jerrygarciuh | last post by:
Hi all, I was just wondering what popular opinion is on PHP giving this warning: Warning: Invalid argument supplied for foreach() in /home/boogerpic/public_html/my.php on line 6 when...
0
by: Jan | last post by:
I store sql-commands in a database table. In the first step I get the sql command out of the database table with embedded sql. In the second step I try to execute the command, which i got from the...
5
by: Brad Williams | last post by:
I'm trying to get clearer on limitations of assignment/modifications within a foreach. Why does the following gives a compilation error if MyType is a struct, but it does not if MyType is a class?...
104
by: cody | last post by:
What about an enhancement of foreach loops which allows a syntax like that: foeach(int i in 1..10) { } // forward foeach(int i in 99..2) { } // backwards foeach(char c in 'a'..'z') { } // chars...
32
by: Joe Rattz | last post by:
Hmmm, I wrote the following code. I want an array of bools and I want to intialize them to false. bool bits = new bool; foreach(bool bit in bits) { bit = false; } The compiler complains...
8
by: Brad Wood | last post by:
When I do this: foreach( Button btn in myForm.Controls ) An exception is raised when no buttons exist. I would simply expect execution to continue after the foreach loop (just as would be the...
3
by: Primera | last post by:
I am trying to use the below to return different values of an int variable, but I seem to be running into scope issues as I cannot use the iSize variable outside of the foreach block. Any help is...
5
by: james | last post by:
Hey Guys, Would anyone mind explaining why a foreach will implicitly do unsafe casts, and if there is a way to turn this off? Here is an example: ulong vals = new ulong { ulong.MaxValue };...
8
by: Bill Butler | last post by:
"raylopez99" <raylopez99@yahoo.comwrote in message news:bd59f62a-5b54-49e8-9872-ed9aef676049@t54g2000hsg.googlegroups.com... <snip> I don't think "right" is the correct word. There are many...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.