Kristoffer Rigbolt
Kristoffer Rigbolt

Reputation:

Initializing System.Array?

Why does Visual Basic compiler complain?

Dim finalArray As Array = New Array

Upvotes: 3

Views: 3053

Answers (6)

Meta-Knight
Meta-Knight

Reputation: 17845

As others said, it DOES complain. awe is right, you have to specify the type and size of the array. You can do it with an array initializer:

Dim finalArray As Array = New Integer() {1, 2, 3}

But when you assign it to an Array, you lose type information. It is better to do:

Dim finalArray As Integer() = {1, 2, 3}

This way you have an array of integer that you can access by index, and you can still use all the methods of Array.

Upvotes: 2

Joe Chung
Joe Chung

Reputation: 12123

Array is an abstract class (MustInherit in VB terms). You cannot instantiate an abstract class.

Upvotes: 4

Svetlozar Angelov
Svetlozar Angelov

Reputation: 21660

EDIT:(after Joe Chung remark)

msdn:

A MustInherit class cannot be instantiated directly, and therefore the New operator cannot be used on a MustInherit class. Although it's possible to have variables and values whose compile time types are MustInherit, such variables and values will necessarily either be a null value or contain references to instances of regular classes derived from the MustInherit types.

Upvotes: 2

awe
awe

Reputation: 22442

You must specify type and size of the array:
Example creating array of String, size is 5:

Dim finalArray As Array = Array.CreateInstance(GetType(String), 5)

Upvotes: 0

StingyJack
StingyJack

Reputation: 19469

Why not

Dim finalArray as New ArrayList()

Really, if you are only storing a certain type of object, you should be using generics.

Dim finalArray as New List(Of Integer)
Dim finalArray as New List(Of String)
Dim finalArray as New List(Of YourFavoriteObject)

(And dont be a sloppy VB6 programmer... add those perens for constructors and other methods calls.)

Upvotes: 1

Fredou
Fredou

Reputation: 20100

it does for me, which version of Visual Studio are you using?

 Error  1   'New' cannot be used on a class that is declared 'MustInherit'. C:\Documents and Settings\---\My Documents\Visual Studio 2008\Projects\---\Default.vb   171 39  ---

Upvotes: 1

Related Questions