tags:

views:

73

answers:

3

I have an object (Incident) which has a child object (Action). An Incident may have zero or or one Action objects. I'm attempting to test whether the Incident object has a child Action object with the following code:

If Not MyIncident.Action Is Nothing

In theory this should work but for some reason the child Action object is mysteriously intantiated (with no values). This instantiation seems to happen on the Else line of an If Else statement where I check the ID property of the Incident object to work out whether it has been saved to the database or not:

If MyIncident.ID = 0 Then

  Me.cmdAddNote.Visible = False
  Me.dgvNotes.Visible = False
  Me.DefaultHitsAndMisses()

Else 
  Me.cmdAddNote.Visible = True

  If Not MyIncident.Action Is Nothing Then
    Me.cboCorrectiveActionStatus.SelectedValue =  Me.MyIncident.Action.Status.ID  
  End If
End If

MyIncident.Action is Nothing on the first line of the If statement but seems to be instantiated between this and the Else line (in this example only the else case would be executed).

The Action object is otherwise instantiated if required when the Incident object is populated, if the Incident object does not have an associated Action then the Action object is explicitly left uninstantiated.

I was hoping to base some logic on whether the Action object is nothing or not but it does not seem to be a reliable check.

Can anyone shed some light on this?

Note: apologies but the code sample does not seem to want to mark-up properly!

+1  A: 

Is your Action a Structure or a class? Structures can't be null.

Rytmis
+1  A: 

Is it defined with As New? Or perhaps a struct?

Marc Gravell
A: 

Ha! I trying to be clever and actually was being dumb, my Action property was constructing a new instance of the object each time it was called and checking the database for the appropriate data. I failed to set the Action member variable back to nothing if the data could not be loaded. I've amended the property to return nothing if this occurs and now everything works as expected. I was trying to be clever by 'lazy loading' the Action object. That'll learn me.

Thanks to all who offered help.

Simon