Reputation: 521
int toAdd = 0;
List<int> list = new List<int> {1500, 1500, 1200, 1200, 1100, 1100, 1100, 1100, 1000, 1000, 900, 900, 600, 600, 600, 600, 400, 400, 400, 400};
for (int i = 0; i < list.Count; i++)
{
if ((toAdd += list[i]) <= (3000 - list[i]))
{
This c# code works, this vb code doesn't:
Dim toAdd As Integer = 0
Dim list As New List(Of Integer)() From {1500, 1500, 1200, 1200, 1100, 1100, 1100, 1100, 1000, 1000, 900, 900, 600, 600, 600, 600, 400, 400, 400, 400}
For i As Integer = 0 To list.Count - 1
If (toAdd += list(i)) <= (3000 - list(i)) Then
I've identified the problem being the '+=' operator, if i delete the '=' it magically works.
Does vb.net handle the '+=' differently than c#? I can't understand how am i supposed to do what i'm trying to do inside the if statement in vb.
Upvotes: 1
Views: 124
Reputation: 133995
You can't do that in Visual Basic.
In C#, assignments are considered expressions. In VB they're statements, but not expressions. So this statement is valid in C#, but not VB (even when you remove the semicolon):
a = b += 12; // works in C#, but not in VB
Or, said another way, assignment expressions in C# return a value. In VB, assignment statements do not return a value.
Upvotes: 6
Reputation: 475
This should let you do what you need to do.
Dim toAdd As Integer = 0
Dim list As New List(Of Integer)() From {1500, 1500, 1200, 1200, 1100, 1100, 1100, 1100, 1000, 1000, 900, 900, 600, 600, 600, 600, 400, 400, 400, 400}
For i As Integer = 0 To list.Count - 1
toAdd = toAdd + list(i)
If toAdd <= (3000 - list(i)) Then
Upvotes: 4
Reputation: 3752
I don't think VB.Net supports what you're trying to do. Consider x = y = z
. It won't evaluate that as set y = z, then set x = y
, it will evaluate it as set x equal to the result of whether y is equal to z
. I think it expects the += to be an entire statement, and not part of a subexpression. Its the presence inside the if that is screwing it up. Thus, I think the best result is to remove that from the if statement.
For i As Integer = 0 To list.Count - 1
toAdd = toAdd + list(i)
If toAdd <= (3000 - list(i)) Then
Upvotes: 1