Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

function returns an arraylist

Status
Not open for further replies.

jazzmaster111

Programmer
May 2, 2005
25
0
0
MX
Hi:

I 'm declaring an arraylist and I want to make it equal to a function that returns an arraylist.
This is my code

Dim array1 As New ArrayList()

array1=makeArray2()

Function makeArray2() as ArrayList

Dim array2 As New ArrayList()

array2.Add("hi")
array2.Add("hello")

Return array2
End Function

I get a System.NullReferenceException on this line

array1=makeArray2()

what could be wrong?

Thanks!!
 
I think this should be:
Code:
Dim array1 As ArrayList()


Have a great day!

j2consulting@yahoo.com
 
Interestingly, both of these produce the same results - two MessageBoxes, one with "hi" and the other with "hello"

Code:
 Function makeArray2() As ArrayList

    Dim array2 As New ArrayList
    array2.Add("hi")
    array2.Add("hello")
    Return array2

  End Function

  Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

    Dim array1 As New ArrayList
    array1 = makeArray2()
    For a As Integer = 0 To array1.Count - 1
      MessageBox.Show(array1(a).ToString)
    Next

  End Sub

Code:
 Function makeArray2() As ArrayList

    Dim array2 As New ArrayList
    array2.Add("hi")
    array2.Add("hello")
    Return array2

  End Function

  Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

    Dim array1 As ArrayList
    array1 = makeArray2()
    For a As Integer = 0 To array1.Count - 1
      MessageBox.Show(array1(a).ToString)
    Next

  End Sub


Because the New is in the Function, it isn't necessary to use New for array1 (an instance of the array is created in the function). Dim array1 As New ArrayList is unnecessary, but shouldn't cause a problem.

Are you sure there is nothing else in your code that could be causing the problem?
 
You don't need to instantiate (new) Array1. In the makeArray2 method you are returning a reference to an instantiation of an array list. So when you set Array1 = makeArray2 it is assigning the memory address of the object returned from MakeArray2 to Array1.

-Rick

VB.Net Forum forum796 forum855 ASP.NET Forum
[monkey]I believe in killer coding ninja monkeys.[monkey]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top