Returning empty UDT From a function
I have written a function that returns a User Defined Type.
How can i return a empty UDT in case of any error from the function?
I tried setting function to 'Nothing',but it is throwing 'Object Re开发者_如何学Pythonquired' error.
Thanks in advance.
If at all possible, use a Class/Object instead. Even doing something as simple as turning this type:
Public Type EmpRecord
FName As String
LName As String
HiredDate As Date
End Type
into a class can be done by adding a Class to your project called EmpRecord and including just this in it:
Public FName As String
Public LName As String
Public HiredDate As Date
Then you can return Nothing from a function that gets an error while retrieving the record.
In VB6, a user-defined type is a "value type", while a class is a "reference type". Value types are typically stored on the stack (unless they're a member of a class). Reference types are stored as a pointer on the stack pointing to a place in the heap where the actual instance data is stored.
That means a reference to a class can be Nothing
(the pointer is zero), whereas a value type can't.
There are multiple ways to solve your problem:
- Add a
Boolean
member to your user-defined type to indicate success or failure. - Create another "wrapper" UDT like (see below) and return it from your function.
- Change your UDT into a class, which can be
Nothing
(as tcarvin said). - Write the function to return a
Boolean
and take aByRef
parameter. The results are written to the parameter passed in if the function result isTrue
. (A lot of people don't like this, but it's a common solution you should be aware of.)
Wrapper:
Public Type Wrapper
Success As Boolean
Inner As YourOriginalUDT
End Type
Function with ByRef:
Function Foo(ByRef Result As YourOriginalUDT) As Boolean
...
If Success Then
Foo = True
Result.A = A
Result.B = B
Result.C = C
... etc. ...
End If
End Function
A UDT can't be empty. You can either use a "dummy" unintialised UDT, or just set all it's members back to the default values.
精彩评论