In C#, I can declare an array variable like this
object[] Parameters;
and initialize it like this:
Parameters = new object[20];
In Visual Basic, declaring and initializing an array is easy:
Dim Parameters(19) As Object
Dim Parameters As Object(19) ' Alternative syntax
How would I initialize an array variable that has already been declared in VB.NET?
Parameters = New Object(19)
doesn't work.
For example, how would I translate the following to VB.NET?
int value = 20;
object[] Parameters;
if (value > 10)
{
Parameters = new Object[20];
}
Basically the same Visual Basic code as the others, but I'd use the opportunity to add a bit of style:
Dim value = 20 ' Type inference, like "var" in C#
Dim parameters() As Object ' Could also be "parameters As Object()"
If value > 10 Then
parameters = New Object(19) {} ' That's right, Visual Basic uses the maximum index
End If ' instead of the number of elements.
Local variables (parameters
) should start with a lowercase letter. It's an established convention and it helps to get correct syntax highlighting in Stack Overflow (this also applies to the original C# code).
So, why are the braces {}
required in Visual Basic? In Visual Basic, both method calls and array access use parenthesis (...)
. Thus, New X(4)
could mean:
X
and pass 4
to the constructor,X
.To distinguish the two cases, you use the array initializer syntax in the second case. Usually, the braces contain actual values:
myArray = New Integer() {1, 2, 3}
Dim value As Integer = 20
Dim Parameters() as object
If value > 10 then
Parameters = new Object(value - 1){}
end if
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With