4

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];
}
0

3 Answers 3

7

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:

  • Create a new object of type X and pass 4 to the constructor,
  • Create a 5-element [sic] array of 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}
Sign up to request clarification or add additional context in comments.

Comments

6
Dim value As Integer = 20
Dim Parameters() as object
If value > 10 then
  Parameters = new Object(value - 1){}
end if

Comments

4

If you are lazy like me you could use an online converter which yields:

Dim value As Integer = 20
Dim Parameters As Object()
If value > 10 Then
    Parameters = New [Object](19) {}
End If

And if you are not like me and want to learn VB.NET head over to the documentation of the VB.NET syntax and start reading.

2 Comments

If you've programmed in VB.NET for any length of time, you may consider replacing the constant 19 with (value - 1). Will save you some headache/time if value variables value changes. That's the problem with online converters.
@CommonSense, luckily I had never had to use this language in my programming career. And when occasions presented, I simply rewrote the code to C# as I just can't stand VB.NET.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.