vb6

How can I convert this VB6 code to C# while maintaining the original logic?


I'm working on modernizing a VB6 application by converting it to C#. One challenge I’ve encountered is translating certain VB6 patterns to their C# equivalents, especially when dealing with APIs and data structures.

Dim myArray(1 To 5) As Integer
Dim i As Integer

For i = LBound(myArray) To UBound(myArray)
    myArray(i) = i * 10
Next i

Debug.Print myArray(3)

I tried converting it like this:

int[] myArray = new int[5];

for (int i = 0; i < myArray.Length; i++)
{
    myArray[i] = i * 10;
}

Console.WriteLine(myArray[2]); // Equivalent to VB6's myArray(3)?

It works, but there are a few things I'm unsure about:

In VB6, arrays start at 1 (or a custom lower bound). In C#, arrays are zero-based. How do I properly account for this when migrating more complex VB6 logic?

How should I handle VB6's LBound and UBound when they appear in larger projects? Is there a C# equivalent or a better migration pattern?


Solution

  • To replicate a 1-based array, I adjusted the loop to shift the logic while keeping the C# array itself zero-based. This ensures I don’t lose compatibility with idiomatic C# practices. Also in C#, LBound isn't needed since arrays always start at 0. For UBound, I use the Length and subtract one to get the last index.

      // Since VB6 arrays often start at 1, I account for that by adjusting the loop
        int[] myArray = new int[5];
        
        // Populate the array
        for (int i = 1; i <= myArray.Length; i++) // Mimics 1-based logic
        {
            myArray[i - 1] = i * 10; // Offset by -1 to account for zero-based indexing
        }
        
        // Access the "3rd" element in 1-based terms (index 2 in 0-based terms)
        Console.WriteLine(myArray[2]);
    

    This worked well when directly porting code but allowed the C# array to remain zero-based.

    In VB6, Debug.Print outputs to the Immediate Window. I used Console.WriteLine. For GUI-based apps, something like MessageBox.Show might be closer.