2

I am getting an exception when running the following code.

Public Function getSongs() As Song()
   ' Dim dir As New DirectoryInfo(Application.ExecutablePath)
     Dim dir As New DirectoryInfo(directory)
     Dim songsInDir() As Song = Nothing
     Dim i As Integer = 0
     For Each file As FileInfo In dir.GetFiles()
        'only read ".mp3" files
        If file.Extension = ".mp3" Then
            songsInDir(i) = New Song(file.Name)
            i = +i
        End If
    Next
    Return songsInDir
End Function

I get an error on line:

songsInDir(i) = New Song(file.Name)

I get an uncaught exception that says:

"Object reference not set to an instance of an object."

The song object has a:

Public Sub new(By Val filename as String)

... sub that sets a variable and retrieves file info (this code works)

Any help would be appreciated!

0

3 Answers 3

2

Try using a list:

Public Function getSongs() As Song()
  Dim dir As New DirectoryInfo(directory)
  Dim songsInDir() As New List(of Song)
  For Each file As FileInfo In dir.GetFiles()
    'only read ".mp3" files
    If file.Extension = ".mp3" Then
      songsInDir.Add(New Song(file.Name)
    End If
  Next
  Return songsInDir.ToArray()
End Function
Sign up to request clarification or add additional context in comments.

Comments

0

Your problem is that arrays need a size when they're initialized and setting it to Nothing gives you exactly that. Give the array a size and don't set it to Nothing. Also, there's a much cleaner way to do this.

Public Function getSongs() As Song()
    Dim songFiles As String() = Directory.GetFiles(directory, "*.mp3")
    Dim songsInDir(songFiles.Length) As Song
    Dim i As Integer = 0
    For Each file As String In songFiles
        songsInDir(i) = New Song(Path.GetFileName(file))
        i = +i
    Next
    Return songsInDir
End Function 

Comments

-1

You should specify the array size

Dim i as Integer = dir.GetFiles().count or dir.FilesCount()

Dim songsInDir(i) As Song = Nothing

or you can use dynamic array

put this line inside your for loop

ReDim Preserve songsInDir(i)

3 Comments

I don't know why someone VoteDown for my answer? While its correct!!
ReDim Preserve is not a good method to use as it wastes resources everytime you reallocate the array.
It was alternative solution,, i have provide two for him.!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.