简体   繁体   中英

Populating Arraylist in VB.NET?

I have a Function that returns a struct in VB.NET :

Public Shared Function StoreData(Byval abc as store) as pcStruct
Dim st as new pcStruct

For each pc as pent in abc.route
  st.stra.Add("test")
next
st.message="Successfully uploaded"

Return st
End Function

Where as in my struct I have two variables:

  1. stra is an Arraylist
  2. message is a string

When I try to populate the structure as shown above, I get an a nullvalue exception. What am I doing wrong?

The st.stra is not initialized

Try something like:

Dim arr as new ArrayList()
st.stra=arr

before you use st.stra.Add

Ngu's answer is most likely the problem.

Specifically, remember that Structures can have constructors. If you haven't written one for your pcStruct structure, you might want to consider it:

Public Structure pcStruct

   Private thisMessage As String
   Private thisList as ArrayList

   Public Sub New()
      thisList = New ArrayList()
   End Sub 

   Public Property stra As ArrayList
      Get
         Return thisList
      End Get
   End Property

   Public Property Message As String
      Get
         Return thisMessage
      End Get
      Set
         thisMessage = Value
      End Set
   End Property

End Structure

Some argue that it's not necessary to do this in the constructor, but that you should simply do it where the member variable is declared. There's some evidence that this performs better, but I would argue that this will depend on how many of these objects you're declaring. If you're not declaring vast amounts of them, the performance benefit does not outweigh the clarity and extensibility benefit of placing your initialization code in one place. But, as must be pointed out, that is entirely my opinion and must be taken with both a grain of salt and an air freshener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM