0

I want to add dates to an array given start and end dates.

I already tried declaring it as an Array and an ArrayList but it gave the same error at the same exact line. Here is the sample code:

Dim startP As DateTime = New DateTime(2019, 3, 27)
Dim endP As DateTime = New DateTime(2019, 3, 30)
Dim CurrD As DateTime = startP
Dim DateArray As ArrayList

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    While (CurrD <= endP)
        DateArray.Add(CurrD)
        CurrD = CurrD.AddDays(1)
    End While
End Sub

Both gave the error "NullReferenceException was unhandled"

Trevor
  • 7,777
  • 6
  • 31
  • 50
MacNuggets
  • 31
  • 5
  • 3
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Trevor Mar 26 '19 at 12:12

3 Answers3

1

You are getting error due to not initialize DateArray. Do it like :

Dim DateArray As New ArrayList
Md. Suman Kabir
  • 5,243
  • 5
  • 25
  • 43
1

Lists are probably a better choice. Note how the list in the example is initialized.

Dim startP As DateTime = New DateTime(2019, 3, 27)
Dim endP As DateTime = New DateTime(2019, 3, 30)
Dim CurrD As DateTime = startP
Dim DateArray As New List(Of DateTime)

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    While (CurrD <= endP)
        DateArray.Add(CurrD)
        CurrD = CurrD.AddDays(1)
    End While
    'where you need an array of DateTime do
    '   DateArray.ToArray
End Sub
dbasnett
  • 11,334
  • 2
  • 25
  • 33
0

You can do something like this.

  Dim date_array As New List(Of Date)
  date_array.Add(New Date()) ' add as much as you want in a loop or manually
  date_array.ToArray() ' to return an array of dates..