Search code examples
vb.netvisual-studio-2017initializationobject-initializers

How to initialize a structure object containing a mix of structure and simple elements?


Using VB.NET 2017, I declared a structure which has two members, one of them is a structure and the other is a string, as follows:

Structure InpFile
    Dim name As String
    Dim reader As StreamReader
    Dim lineIn As String
    Dim lineNum As Integer
End Structure

Structure Opts
    Dim fin As InpFile
    Dim name As String
End Structure

How can an object of type Opts be initialized at declaration time?

For example, one attempt that does not work:

Dim obj as Opts = {.fin.name = "filename.txt", .fin.lineNum = 0, .name = "JohnnyMnemonic"}

Solution

  • You have to use the With statement.

    Dim obj As New Opts With {.fin = New InpFile With {.name = "filename.txt", .lineNum = 0}, .name = "JohnnyMnemonic"}