Tuesday, October 21, 2008

Option Strict On causes Disallows Late Binding Error when getting Variant Array from a COM Object

I have several ActiveX controls that I use with .NET. Generally, there are not too many problems using them with .NET, but I have come across one error that was difficult (for me) to solve.

Since the ActiveX controls were originally written for VB6, they return Variants and arrays are returned as Variants of Variants. This is all fine because .NET has an Object type to work with the variants. As a rule, however, I use Option Strict On because if you don't use this option, Dotfuscator will really cause problems without letting you know in advance. But the catch is that with Option Strict on, you cannot do something like the following:

Dim varArray as Object
Dim count as Integer

SomeComObject.GetList( varArray, count )

For i as Integer = 0 to count - 1

Debug.WriteLine( varArray(i).ToString )


varArray will return list of integers, but as a Variant Array of Variant Integer values.

The code above will not work with Option Strict On because the varArray(i) is late bound and this is not allowed. My first though was to try:

Dim val as integer = CType( varArray(i), Integer)

This doesn't work or any similar cast.

The only way solution (and there are probably others) is to cast the Variant array as an Integer array like:

Dim vArray() as Integer = CType( varArray, Integer())

Then the vArray is a regular Integer Array.

No comments: