We have noticed a weird behavior with ADOX objects. For example, consider the following VB6 code:
Sub Test(ByVal con As ADOX.Catalog)
Dim i As Integer
For i = 0 To con.Tables.Count – 1
Sub DisplayTableName(tableName As String)
Notice that the tableName parameter is taken by-reference, even though it isn’t assigned inside the DisplayTableName procedure. This code behaves correctly under VB6 but not under VB.NET. In fact, the ByRef argument causes the Name property of the ADOX.Table object to be reassigned on exit from the DisplayTableName procedure, which in turn causes a COMException error with the following error message:
Table 'XYZ' already exists
In other circumstances you might have different error messages. For example, even if the assignment to the Table’s Name property is successful, such an assignment causes the Tables collection of the Catalog object to be rebuilt and the Table being modified is moved to the end of the collection itself.
If the assignment occurs inside a For Each loop, VB.NET throws an exception because a collection can’t be modified while it is being enumerated. If it occurs inside a For loop – as in previous code – it may cause certain tables to be skipped during iteration and certain other tables to be processed twice, but you get no exception and the bug might go unnoticed.
All these issues can be fixed by ensuring that the property of the ADOX object be passed using by-value rather than by-reference semantics. In most cases the receiving parameter is (implicitly) declared ByRef only because this keyword is assumed by default under VB6 and you can safely add an explicit ByVal keyword in the original VB6 code.
If the parameter does require by-reference semantics, you must ensure that you pass the ADOX property by value, as in this code:
DisplayTableName con.Tables(i).Name & ""