Apoorv Apoorv - 3 months ago 8x
Vb.net Question

IndexOutOfRange Exception in code converted from VB to C#

I have this VB code

Public Function InitJobTicketConcaveItemsType() As JobTicketConcaveItemsType
Dim OutData As JobTicketConcaveItemsType
With OutData
.NumJobItems = 1
ReDim .JobItems(.NumJobItems - 1)
.JobItems(0) = JobDataConcaveEnum.JDBDryData
End With
Return OutData
End Function

The converted C# code

public static JobTicketConcaveItemsType InitJobTicketConcaveItemsType()
JobTicketConcaveItemsType OutData = default(JobTicketConcaveItemsType);
var _with25 = OutData;

_with25.NumJobItems = 1;
// ERROR: Not supported in C#: ReDimStatement - replaced with the statement below
Array.Resize(ref _with25.JobItems, _with25.NumJobItems - 1);

_with25.JobItems[0] = FrontEndEnums.JobDataConcaveEnum.JDBDryData;
return OutData;

When I try to run the application , I get a the Error IndexOutOfRangeException was unhandled. I have made sure to use Array.Resize() to reallocate the array

The code in VB doesn´t give errors. Any clues ?

JDBDryData has been defined as below

public enum JobDataConcaveEnum
JDBWetData = 0,

I get the error at the statement



In VB array declarations, you specify the last valid index:

'Declare a single-dimension array of 5 values
Dim numbers(4) As Integer 

In C# array declarations, you specify the length of the array.

That means that you should always add 1 when converting a VB array declaration to a C# one. So, simply, don't subtract that 1:

Array.Resize(ref _with25.JobItems, _with25.NumJobItems);