> > 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