Home > Mobile >  How to perform object initializer for a list property in VB.NET
How to perform object initializer for a list property in VB.NET

Time:10-12

I am trying to implement object initializer. All the classes are already created by someone else. I cannot change.

I have a class Ins.vb that has a list as a property

Partial Public Class Ins
  Private itemField As Item1
  Private sizeCodeListField() As SizeCode  'This is the property

  Public Property Item() As Item1
    Get
      Return Me.itemField
    End Get
    Set
      Me.itemField = value
    End Set
  End Property

  Public Property SizeCodeList() As SizeCode()
    Get
      Return Me.sizeCodeListField
    End Get
    Set
      Me.sizeCodeListField = value
    End Set
  End Property
End Class

Item1.vb

Public Partial Class Item1
  Private codeField As String
  
  Public Property Code() As String
    Get
      Return Me.codeField
    End Get
    Set
      Me.codeField = value
    End Set
  End Property
End Class

SizeCode.vb

Partial Public Class SizeCode
  Private sizeCode1Field As String
  Private sizeCodeDescriptionField As String

  Public Property SizeCode1() As String
    Get
      Return Me.sizeCode1Field
    End Get
    Set
      Me.sizeCode1Field = value
    End Set
  End Property
  Public Property SizeCodeDescription() As String
    Get
      Return Me.sizeCodeDescriptionField
    End Get
    Set
      Me.sizeCodeDescriptionField = value
    End Set
  End Property
End Class

This is how I am trying to do object initialization

Dim myVar = New Ins _
  With {.Item = New Item1 With {.Code = "I"},
        .SizeCodeList = New SizeCode With {.SizeCode1 = "S", .SizeCodeDescription = "Description"}}  'I am getting an error here

The error is Value of type 'SizeCode' cannot be converted to 'SizeCode()'

I am not sure how to implement this and I am stuck.

CodePudding user response:

Your syntax should be something like this:

            Dim myVar = New Ins _
  With {.Item = New Item1 With {.Code = "I"},
        .SizeCodeList = New SizeCode() {New SizeCode With {.SizeCode1 = "S", .SizeCodeDescription = "Description"}}}  

CodePudding user response:

You are initializing .SizeCodelist as a SizeCode but it should be a list. I did not test it but this should work I think:

 Dim myVar = New Ins With
{.Item = New Item1 With {.Code = "I"},
 .SizeCodeList = New List(Of SizeCode)}

Dim newSizeCode As New SizeCode With {.SizeCode1 = "S", .SizeCodeDescription = "Description"}

myvar.SizeCodeList.add(newSizeCode)
  • Related