Need help converting c # to vb. "Array initializer missing 1 element"

I am trying to execute the following code from C # to Vb using 3.5 framework.

Here is the C # code I'm having trouble with.

MethodInfo mi = typeof(Page).GetMethod("LoadControl", new Type[2] { typeof(Type), typeof(object[]) });

      

I thought it would be like this in VB;

Dim mi As MethodInfo = GetType(Page).GetMethod("LoadControl", New Type(2) {GetType(Type), GetType(Object())})

      

but I am getting the following error: "Array initializer does not contain 1 element"

Another line I ran into and get the same error is

control = (Control) mi.Invoke(this.Page, new object[2] { ucType, null });

      

I tried this in vb but it doesn't work.

control = DirectCast(mi.Invoke(Me.Page, New Object(2) {ucType, Nothing}), Control)

      

ucType is defined as follows

Dim ucType As Type = Type.[GetType](typeName(1), True, True)

      

Any help would be greatly appreciated.

+1


source to share


6 answers


VB.Net arrays are 0-based, but are declared using the highest index, not cardinality. Thus, an array of 10 elements, indexed 0..9, is declared as Item (9).

With that said, the real solution to your problem is to let the compiler figure out the length of the array, for example:



Dim mi As MethodInfo = GetType(Page).GetMethod("LoadControl", New Type() {GetType(Type), GetType(Object())})

      

+6


source


In VB.NET, an array declaration takes an upper bound on an array, not a C #-like length (kind of silly if you ask me). Because of this, you need to decrease the number passed to the array declarations by 1 (since arrays are zero based).



+5


source


For the first line, you need to change the new type (2) to the new type (1).

Dim mi As MethodInfo = GetType(Page).GetMethod("LoadControl", New Type(1) {GetType(Type), GetType(Object())})

      

In VB.Net, the number specified in the array initializer is the highest available index with respect to length. The second line you talked about has the same problem and solution.

+3


source


VB uses upper bounds as an argument for arrays.

new byte[X]

new byte(X) 'wrong, 1 more element
new byte(X-1) 'correct, kinda confusing
new byte(0 to X-1) 'correct, less confusing

      

I suggest using the style (0 to X-1) because it is much clearer. This was much more important in the vb6 days, when array (X) could mean 0 to X or 1 to X depending on the context.

+2


source


It will be like this:

Dim mi As MethodInfo = GetType(Page).GetMethod("LoadControl", New Type(1) {GetType(Type), GetType(Object())})

      

The other will be -

control = DirectCast(mi.Invoke(Me.Page, New Object(1) {ucType, Nothing}), Control)

      

+1


source


There is an online version http://converter.telerik.com that converts C # to VB and vice versa.

+1


source







All Articles