Function using arraylist question / error

ckelsoe

Member
Joined
Feb 12, 2005
Messages
20
Location
Winchester, VA
Programming Experience
10+
I have a function that returns an array list. The function looks something like this:

Protected Function RetrieveExtensions(ByVal sourceDir As System.IO.DirectoryInfo) As ArrayList

Dim file As System.IO.FileInfo
Dim strExtension As String
Dim childDir As System.IO.DirectoryInfo
For Each file In sourceDir.GetFiles()
strExtension = file.Extension
RetrieveExtensions.Add(strExtension) ' Code fails here
Next

For Each childDir In sourceDir.GetDirectories()
RetrieveExtensions(childDir)
Next

End Function

The problem I am having is that I get the error "Object reference not set to an instance of an object." when the code hits the line marked above. So far I am unable to understand why this would fail. It works in a normal arraylist.

Thanks for any help in advance.

Charles
 
It's hard for me to explain, so here a code sample:
VB.NET:
Protected Function RetrieveExtensions(ByVal sourceDir As System.IO.DirectoryInfo) _
  As ArrayList
    Dim al As New ArrayList()
    Dim file As System.IO.FileInfo
    Dim strExtension As String
    Dim childDir As System.IO.DirectoryInfo
    For Each file In sourceDir.GetFiles
        strExtension = file.Extension
        al.Add(strExtension) ' Code fails here
    Next
    For Each childDir In sourceDir.GetDirectories()
        al.AddRange(RetrieveExtensions(childDir))
    Next
    Return al
End Function
 
So basically, you are encapsulating the call to the function by having it return an array back to the origional array.

One problem that I am having with vb.net is trying to overcomplicate the code. Once a person understands the power of .net, things are simpler. Someday I will get there :)

THanks very much for the help.
 
The reason your original was failing was you were using the Function name to add to the arraylist that you wanted to return. What you want to do is like Paszt shows with the Dim al as New ArrayList(), then using that to add what you want. When you are finished, return al.

That is how I do all my functions. Since you can recursively call a Function from within the function, you would have to look twice to see if you were calling the same function or something else entirely.
 
That was one of the new things I learned about vb.net in this project. I find that it is easy to make things harder than they should be with VB.net because of not understanding the power of it.


Thanks to all of your help.

Charles
 
Back
Top