3

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"}
ysap
  • 7,723
  • 7
  • 59
  • 122
  • Structures should be immutable. This would be better as a class rather than a structure. – Chris Dunaway Aug 01 '18 at 14:42
  • @ChrisDunaway - immutable as in unchangeable (or constant)? Can you please explain why you think this should be the case? – ysap Aug 01 '18 at 16:11

1 Answers1

6

You have to use the With statement.

Dim obj As New Opts With {.fin = New InpFile With {.name = "filename.txt", .lineNum = 0}, .name = "JohnnyMnemonic"}
the_lotus
  • 12,668
  • 3
  • 36
  • 53
  • Thanks. I did try many permutations of using `With`, `=`, etc. I guess the missing permutation was assigning `.fin` using `=` and not `With`. – ysap Aug 01 '18 at 13:48
  • And you have to use the "new" operator, normally on a structure you don't need new – Brain2000 Apr 02 '21 at 00:51