Reputation: 10144
I want to create a function that takes an argument of a reference to an array of at least a certain length, so that the function will know that there is enough space for it to write all the data it needs to write to the array.
Is this possible in VB.NET?
At the moment I am ReDim
'ing the referenced array but I'm not sure if this is really working or not. (I guess I can test this method and break it by passing an array to small and see, will try that momentarily)
Public Function Foo(ByRef data() As Byte) As Boolean
If Data.Length < 4 Then
ReDim Preserve ProductId(4)
End If
' Other operations that put 4 bytes on the array...
Return True
End Function
Even if that method works, I'm not convinced that re-sizing the users array is really that great of an idea in comparison to just informing them that the parameter specifies a length of 4 somehow... Is there a better way of managing this?
Upvotes: 2
Views: 414
Reputation: 498
I'd actually try something similar to what you're doing here, but like this:
Public Function Foo(ByRef data() As Byte) As Boolean
If Data.Length < 4 Then
Return False
End If
'Other operations...
Return True
End Function
Or maybe this:
Public Function Foo(ByRef data() As Byte) As String
If Data.Length < 4 Then
Return "This function requires an array size of four"
End If
'Other operations...
Return "True"
End Function
Then, in your calling function, this:
Dim d As Boolean = Convert.ToBoolean(Foo(YourArray))
Then you can bubble up the error to the user, which is what you were looking to do, right?
Upvotes: 1
Reputation: 46929
Your function should take in a stream instead.
Public Function Foo(ByVal stream As Stream) As Boolean
'Write bytes to stream
End Function
For eaxmple you can call your method using a MemoryStream
Dim stream = new MemoryStream()
Foo(stream)
Dim array = stream.ToArray() 'Call ToArray to get an array from the stream.
Upvotes: 3
Reputation: 1118
No as far as I know you can't specify the size of the array in the parameters list.
You can however, check the size of the array like you are currently doing and then throw an ArgumentException. This seems to be one of the most common ways to validate data at the start of a method.
Upvotes: 2