473,799 Members | 2,868 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3299

"cody" <pl************ *************@g mx.de> wrote in message
news:uY******** ******@TK2MSFTN GP10.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<objec t>();
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
3229
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 presented with an indefined variable. It makes sense to me to warn if an unacceptably defined var is passed but it
0
10220
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 database table, using dynamic sql. Executing 'EXEC SQL DESCRIBE SELECT LIST FOR S INTO select_dp;' the error code -2149 is returned That means "Specified partition does not exist". Does anybody know if it is a database problem or a problem of
5
2972
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? public struct MyType // change to class, and it compiles clean { public int f; } public void foo()
104
7205
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 foeach(Color c in Red..Blue) { } // using enums It should work with all integral datatypes. Maybe we can step a bit further: foeach(int i in 1..10, 30..100) { } // from 1 to 10 and 30 to hundred
32
6525
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 on the "bit = false;" stating that bit is read-only.
8
2110
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 case with a regular for loop when the second expression is false when the loop begins). Is there an explanation for this?
3
2441
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 appreciated. public int CalcDiskSpace(string strComputer) { ManagementScope oMS = new ManagementScope("\\\\" + strComputer); ObjectQuery oQuery = new ObjectQuery("Select Size From Win32_DiskDrive"); ManagementObjectSearcher oSearcher = new
5
2766
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 }; foreach (uint x in vals) Console.WriteLine(x);
8
273
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 other words that could fill in the blank though. "Or am I _______ as usual?"
0
9550
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10248
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10032
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7573
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6811
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5597
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4148
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2942
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.