I cannot add an item if no item exists before

  • Thread starter Thread starter nime
  • Start date Start date
N

nime

Hi!

If a collection ( here; a List) is Nothing then I cannot use .Add method,
It causes an error:
System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object."

First I try .Add method, then I try to create an instance and use it, if error occurs.

Am I doing it right or is there a better way to resolve this error?

****************************************************
Public Structure WingStructure
Public ShipType As String
Public ShipCount As Integer
End Structure

Public Structure FleetStructure
Public Wings As List(Of WingStructure)
...
End Structure

...
Dim Fleet As New FleetStructure

'Dummy objects
Dim _wing As New WingStructure
Dim _wings As New List(Of WingStructure)

_wing.ShipCount = 2
_wing.ShipType = "Fighter"

Try
Fleet.Wings.Add(_wing)
Catch ex As Exception
wings.Add(_wing)
Fleet.Wings = _wings
End Try
 
Hi,

You need to create the list before you use it.

Dim Fleet As New FleetStructure

Fleet.Wings = new List(Of WingStructure)

Ken
--------------------
Hi!

If a collection ( here; a List) is Nothing then I cannot use .Add method,
It causes an error:
System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object."

First I try .Add method, then I try to create an instance and use it, if
error occurs.

Am I doing it right or is there a better way to resolve this error?

****************************************************
Public Structure WingStructure
Public ShipType As String
Public ShipCount As Integer
End Structure

Public Structure FleetStructure
Public Wings As List(Of WingStructure)
...
End Structure

...
Dim Fleet As New FleetStructure
'Dummy objects
Dim _wing As New WingStructure
Dim _wings As New List(Of WingStructure)
_wing.ShipCount = 2
_wing.ShipType = "Fighter"
Try
Fleet.Wings.Add(_wing)
Catch ex As Exception
wings.Add(_wing)
Fleet.Wings = _wings
End Try
 
Back
Top