array of objects

M

Michele

Hi,
I have trouble with an array of objects!

I declared a class like this:

Public Class myClass
Public X As String
Public Y As Integer
Public Z As String

Public Sub New()
X = ""
Y = 0
Z = ""
End Sub

End Class

when in another class i try to declare an instance of it

Dim MyArray as New myClass

myArray.X = "ggggg"

it's work fine, but if i try to declare an array of objects using

Dim MyArray() as myClass
myArray(0).X = "ggggg"

i get the following error message:

Unhandled exception "System.NullReferenceException" in myProject.exe

Reference to an object without object instance.

can you help me with it?

thanks

Michele
 
J

Jan Tielens

When you declare an array, you do not filled it with instances yet, so you
need to do this first!


Dim MyArray(10) as myClass
myArray(0) = new myClass()
myArray(0).X = "Testing"

Greetz

Jan Tielens
________________________________
Read my weblog: http://weblogs.asp.net/jan
 
H

Herfried K. Wagner [MVP]

* (e-mail address removed) (Michele) scripsit:
I have trouble with an array of objects!

I declared a class like this:

Public Class myClass
Public X As String
Public Y As Integer
Public Z As String

Public Sub New()
X = ""
Y = 0
Z = ""
End Sub

End Class

when in another class i try to declare an instance of it

Dim MyArray as New myClass

myArray.X = "ggggg"

it's work fine, but if i try to declare an array of objects using

Dim MyArray() as myClass
myArray(0).X = "ggggg"

i get the following error message:

Unhandled exception "System.NullReferenceException" in myProject.exe

The code will only create an array, but it won't instantiate the
objects. You can use 'MyArray(0) = New MyClass()' before accessing one
of its properties to do that. Notice that 'MyClass' is a reserved
keyword in VB.NET.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top