hi,
i have some weird result using for loop...
here it is in vb.net.........
Module Module1
Sub Main()
For i As Integer = 1 To 3
Dim total As Integer
total += i
Console.WriteLine(total)
Next
End Sub
End Module
here it is in c#
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 3; i++)
{
int total = 0;
total += i;
Console.WriteLine(total);
}
}
}
the results are different...
i think because in c#, we cannot use the variable total if uninitialized...
how to go about this?
PvdG42 - 11 Sep 2007 04:50 GMT
> hi,
>
[quoted text clipped - 37 lines]
> i think because in c#, we cannot use the variable total if
> uninitialized... how to go about this?
In both cases, your accumulator should be declared and initialized once
*before the loop begins*. In the C# example it is reinitialized to zero on
each iteration.
Jack Jackson - 11 Sep 2007 06:00 GMT
>hi,
>
[quoted text clipped - 37 lines]
>i think because in c#, we cannot use the variable total if uninitialized...
>how to go about this?
In VB the DIM statement is scoped to the entire method. It is the
same as if you said:
Sub Main()
Dim total As Integer
For i As Integer = 1 To 3
total += i
Console.WriteLine(total)
Next
End Sub
In VB it is not possible to have block-scoped variables.
In the C# example, 'total' exists only inside the for loop. The
variable 'total' is reinitialized each time through the loop. If you
want the C# code to work like the VB code, move the definition of
'total' outside the for loop.
Benjamin Fallar III - 11 Sep 2007 08:56 GMT
thanks jack! that confirms my code :)
>>hi,
>>
[quoted text clipped - 58 lines]
> want the C# code to work like the VB code, move the definition of
> 'total' outside the for loop.