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.
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())})
source to share
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.
source to share
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.
source to share
There is an online version http://converter.telerik.com that converts C # to VB and vice versa.