What To Use Instead of "New" Keyword When Creating Class Array

G

Guest

Hi:

I'm having trouble using an Object which is created based on the following:

Public CarDetail () as Car


Where the CLASS "Car" is defined as:

Public Class Car
Public Doors() as string
Public Color as string
End Class

While it appears that I can create the "CarDetail" Object, and exception is
thrown when I try to refer to anything that is part of "CarDetail".

I am receiving the following error: "Object reference not set to an instance
of an object.".

Ok, so I figure I need to add the "New" Keyword when I instantiate
"CarDetail":

Public CarDetail () as Car -----> Public CarDetail () as New Car

When I do this, the compilier informs me that 'arrays cannot be declared
with 'New'.

Is there an alternative to the "New" keyword that I should use in this case?

Thanks
Paul Auleciems
 
J

Jon Skeet [C# MVP]

Paul Auleciems said:
I'm having trouble using an Object which is created based on the following:

Public CarDetail () as Car

Where the CLASS "Car" is defined as:

Public Class Car
Public Doors() as string
Public Color as string
End Class

While it appears that I can create the "CarDetail" Object, and exception is
thrown when I try to refer to anything that is part of "CarDetail".

I am receiving the following error: "Object reference not set to an instance
of an object.".

Ok, so I figure I need to add the "New" Keyword when I instantiate
"CarDetail":

Public CarDetail () as Car -----> Public CarDetail () as New Car

When I do this, the compilier informs me that 'arrays cannot be declared
with 'New'.

Is there an alternative to the "New" keyword that I should use in this case?

After creating the array, each element of it is null (Nothing). You
need to set the element's value to a new instance of CarDetail before
accessing it.
 
M

Mattias Sjögren

Is there an alternative to the "New" keyword that I should use in this case?

Public CarDetail(N) as Car

to create an array with N+1 elements.



Mattias
 
K

Kevin Yu [MSFT]

Hi Paul,

You have to create each Car object in the array like the following:

For i=0 to N
CarDetail(i) = New Car()
Next i

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 

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