Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop VB.Net to C# Code Conversion

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?

like image 463
Sekhar Avatar asked Aug 12 '26 05:08

Sekhar


2 Answers

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

  • F#: Variables are readonly by default though so this is just consistency with the rest of the language
  • Ada: Disallows assignment of the looping value in for statements

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

like image 192
JaredPar Avatar answered Aug 14 '26 18:08

JaredPar


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?

like image 25
paulsm4 Avatar answered Aug 14 '26 20:08

paulsm4



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!