tags:

views:

166

answers:

6

Why does Visual Basic compiler complain?

Dim finalArray As Array = New Array
+1  A: 

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 ---
Fredou
I think he meant to ask: "Why does it complain?" ...
awe
+1  A: 

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.)

StingyJack
hes using array, not arraylist
Fredou
Thats the point. There is no reason to.
StingyJack
you never know what he need to do, never assume anything :-)
Fredou
Its pretty obvious that anyone doing .NET programming who is using an "Array" is not aware of the multitude of better choices for collections.
StingyJack
Arrays are so 2004. Agree with Jack: if you see yourself using an array in .net, you should look at your code and see if you can do better. One thing though: imo List<Object> is still preferrable to ArrayList.
Joel Coehoorn
If only params would give you the freedom to leave arrays in the dust... =(
Marc
+2  A: 

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.

Svetlozar Angelov
Actually that is his situation.
Joe Chung
+4  A: 

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

Joe Chung
+1. Added some linkage
MarkJ
A: 

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)
awe
+1  A: 

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.

Meta-Knight