Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# to VB.NET array initialization

Tags:

arrays

c#

vb.net

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];
}
like image 859
Rauland Avatar asked Dec 04 '22 07:12

Rauland


2 Answers

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}
like image 182
Heinzi Avatar answered Dec 14 '22 09:12

Heinzi


Dim value As Integer = 20
Dim Parameters() as object
If value > 10 then
  Parameters = new Object(value - 1){}
end if
like image 27
CommonSense Avatar answered Dec 14 '22 08:12

CommonSense