Here's the code in VB.Net
If Not queryItems Is Nothing Then
For Each qItem As String In queryItems
qItem = qItem.ToLower()
Next
End If
and it's "equivalent" code in c# (using sharpdevelop/developerfusion/telerik's converter/VS 2012 "paste as c#" method)
if (queryItems != null)
{
foreach (string qItem in queryItems)
{
qItem = qItem.ToLower();
}
}
The C# compiler (rightly so ) complains with the following
"Cannot assign to 'qItem' because it is a 'foreach iteration variable'"
I am wondering why this behavior is permitted in VB.Net?
The crux of the question appears to be this
I am wondering why this behavior is permitted in VB.Net?
A better question may be the following
Why did C# prevent assignment to the foreach iteration variable?
If you look at the set of lopping constructs and languages C# is the odd ball here. In virtually every other case (even in Java foreach) it is legal to assign to the iteration variable of a looping construct. The only other cases I`m aware of are
for statementsVB.Net is actually more consistent here with the norm than C#.
Unfortunately it's not clear why C# made this choice. There are a lot of speculative answers out there but until Eric or Anders does a blog post on this the real reason will remain unknown
It's perfectly reasonable to want to set each string in (an array? a list?) to lower-case, in a loop.
SUGGESTION: just use a good old "for()" loop -
// Assuming array syntax...
if (queryItems != null)
{
for (int i=0; i < queryItems.Length; i++)
{
queryItems[i] = queryItems[i].ToLower();
}
}
IMHO...
PS: I'm not sure if the VB.Net version ever actually worked as intended. Do you know?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With