Returning Null or Nothing from a VBScript Function?

I am trying to write the equivalent of a VBScript function similar to the following:

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

My assumption will be lower, except that I do not understand the difference between Nothing and Null. As the caller, I would prefer to check if the return value is set 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 
+7
source share
3 answers

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

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

+14
source

Use the second function skeleton. Avoid Null when working with objects due to the flickering Set Assignment.

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

against

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

In your code example, the object will always be Nothing , because this is the last action. Here's 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 

GSerg's answer is correct: you should use Nothing. Also, to see if the object has a null reference, use:

 If Not object Is Nothing Then ' do something End If 
+2
source

All Articles