Search code examples
vb.netdesktop

Problems to fill information of 2 class


I have 2 class in VB.net (Item Class and Tax Class). The Item class calls the Tax class in the form of an array.

See Class (Item-TaX)

Public Class Item
    Public Property taxes As Tax()
    Public Property code As String
End Class

Public Class Tax
    Public Property taxCode As String
    Public Property taxAmount As Integer
End Class

I need to add data to the 2 classes to build a JSON file

I'm doing it my way of thinking as follows:

Dim TaxProduct As New Tax
Dim Product As New Item
TaxProduct.taxCode = "01"
TaxProduct.taxAmount = 1000

Even there is going perfectly and the data is added in the class TaxProduct

Product.taxes = TaxProduct  'This line generates an error
Product.code = "10"

I thank you can help me

I hope you can explain to me how to enter the data in the class


Solution

  • A few changes that woudl be worth considering to your class structure below.

    1. You seem to be storing a dollar amount as an integer. This is bad practice as money is frequently dollars and cents. Consider making that a decimal as below.
    2. If you are dynamically adding tax objects to your item taxes array, you should use a List(of Tax)
    3. I can't confirm here, however, it appears that you are storing a lot of int as string. (think code and tax code). Will those always be an integer value? Would you be better off using an enum of some sort instead. Food for thought.
        Public Class Item
            Public Property taxes As New List(of Tax)
            Public Property code As String
        End Class
    
        Public Class Tax
            Public Property taxCode As String
            Public Property taxAmount As Decimal
        End Class
    

    After making the changes above, your code to new up and fill tax items into your product would look something like the below. Note the use of With is a VB exclusive and is imo just syntactical sugar. It is not an option in most other languages so use it with discretion.

        Dim Product As New Item with {.code = "10" }
        Dim TaxProduct As New Tax with {
            .taxCode = "01",
            .taxAmount = 1000
        }
        
        Product.taxes.add(TaxProduct)