开发者

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:

  1. Add a Boolean member to your user-defined type to indicate success or failure.
  2. Create another "wrapper" UDT like (see below) and return it from your function.
  3. Change your UDT into a class, which can be Nothing (as tcarvin said).
  4. Write the function to return a Boolean and take a ByRef parameter. The results are written to the parameter passed in if the function result is True. (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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜