9

I'm trying to write the VBScript equivalent of a function similar to what's below:

object getObject(str)
{
    if ( ... )
    {
        return object_goes_here;
    }

    return null;
}

My guess would be below, except that I'm not understanding the difference between Nothing and Null. As a caller, I'd rather test if the return value is set by using IsNull() versus X Is Nothing.

Function getObject(str)
    If ... Then
        Set getObject = object_goes_here
        Exit Function
    End If

    Set getObject = Nothing  // <-- or should this be Null?
End Function

3 Answers 3

16

The correct way to not return an object is to return Nothing and test for Is Nothing.

VB's Null is a special value of type Variant/Null. There are other special values, such as Variant/Empty or Variant/Error. They all have their use, but it's not the one.

Sign up to request clarification or add additional context in comments.

2 Comments

How is InStr getting away with it? It looks like it returns the .NET equivalent of a Nullable<int>. w3schools.com/vbscript/func_instr.asp
@jglouie InStr accepts a VARIANT as its parameter, not an object. It then examines the VARIANT and tries to give you what you expected. Returning a Null if a string operand is Null is a very standard common concept coming from databases. As for strings in VB6 (and VBScript), they are not objects anyway, they cannot be Nothing. Well, they sort of can, but that's called vbNullString and is not detected with Is Nothing.
4

Use the second Function skeleton. Avoid Null when dealing with objects, because of the Set Assignment abomination.

Dim oX : Set oX = getObject(...)
If oX Is Nothing Then
   ...
Else
  nice object to work with here
End If

vs

Dim vX : vX = getObject(...) ' <-- no Set, no object
If IsNull(vX) Then
   ...
Else
   no object to work with here
End If

Comments

3

In your sample code, the object gets always Nothing because that is the last action. This is how it should be:

Function getObject(str)
     If ... Then
         Set getObject = object_goes_here
         Exit Function
     End If
     Set getObject = Nothing
End Function

or:

Function getObject(str)
     Set getObject = Nothing  
     If ... Then
         Set getObject = object_goes_here
     End If
End Function

The answer of GSerg is correct: you should use Nothing. Additionally, to see if an object has a null reference, use:

If Not object Is Nothing Then
    '  do something
End If

1 Comment

Oops, I left out the Exit Function line, thanks. That wasn't my question but it'll clarify anyone else searching for this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.