Option Strict possible with FileGet?

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,858
Location
Norway
Programming Experience
10+
I came across some old code that was using the FileGet with binary access, it simply reads a count then reads a dimensioned structure array from the file, similar to this:
VB.NET:
Dim data(count) As structureType
FileGet(fnum, data)
With Option Strict Off the code runs fine. With Option Strict On 'data' gets squiggly:
Option Strict On disallows narrowing from type 'System.Array' to type '1-dimensional array of structureType' in copying the value of 'ByRef' parameter 'Value' back to the matching argument.
Is it possible to do something about this? I know better alternatives exist like the BinaryFormatter, but still was just wondering.
 
The problem is that you are passing 'data', which is type structureType, by reference to a parameter of type Array. FileGet can, in theory, pass back any Array object, so it cannot be assigned back to 'data' safely without a cast, which is not possible using only the argument.

Now, I say "in theory" because I'm guessing that FileGet doesn't actually create a new Array object, but rather the passing by reference is just to maintain the same behaviour as the original VB6 FileGet method. As such, you can probably just force the argument to be passed by value and things will still work, which involves the smallest possible code change to work under Option Strict On:
VB.NET:
Dim data(count) As structureType
FileGet(fnum, [COLOR="Red"]([/COLOR]data[COLOR="Red"])[/COLOR])
You may or may not be aware but wrapping an argument in parentheses forces it to be passed by value, even if the parameter is declared ByRef.

If that doesn't work, you would have to go to this:
VB.NET:
Dim data(count) As structureType
Dim arr As Array = data

FileGet(fnum, arr)

data = DirectCast(arr, structureType())
 
I actually tried the latter earlier, but forgot to send the Array object back to the original variable. Thanks :)

Passing ByVal does not, seems the "connection" is there lost.
 
Back
Top