Search code examples
vb.netvariable-initialization

What does variable-initialization line do in VB.Net?


Can someone please tell what the following line of VB.Net is initializing:

Dim x As SomeType() = New SomeType(0) {}

What holds x variable? Is it an array? How can it be translated to C# for example?

I guess SomeType is probably an anonymous type, but still have no clue...


Solution

  • The line:

    Dim x As SomeType() = New SomeType(0) {}
    

    declares an array of SomeType objects, which can hold one instance of SomeType.

    When declaring an array of objects the value that is passed into the constructor is the max index of the array. So this declaration is basically declaring an array with a length of 1. The {} portion of the line is where you could define the values that should be stored in the array. If you were to change SomeType to integer you could instantiate and fill your array like:

    Dim intArray as Integer() = New Integer(0) {7}
    

    and that would give the first instance stored in the intArray variable a value of 7.

    SomeType is not an anonymous type. SomeType would be a class that would have to be defined somewhere in your app.

    In C# I think the sytax would look like:

    SomeType[] x = new SomeType[0];
    

    I'm not exactly sure how you would accomplish the {} portion of the VB.NET line in C#.