2342G456DI8
2342G456DI8

Reputation: 1809

How to create a class that one of its object is in the type of another class in VB?

Following is my code

Class LIVandOSA
    Public LIV_ As String
    Public OSA_ As String
End Class

Class TestUnitID
    Public SMPSdata As LIVandOSA
    Public SMdata As LIVandOSA
    Public COATEDBARdata As LIVandOSA
    Public CLCLdata As LIVandOSA

    Public Sub New(ByVal s As String)
        SMPSdata.LIV_ = s
    End Sub
End Class

In the main program, I wrote the following code to create a list of TestUnitID and add some element into it.

    Dim a As New List(Of TestUnitID)
    a.Add(New TestUnitID("a1.csv"))
    a.Add(New TestUnitID("a2.csv"))
    TextBox1.Text = a(0).SMPSdata.LIV_

But when I try to compile it, it gives me the following error

An unhandled exception of type 'System.NullReferenceException' occurred in WindowsApplication1.exe

Additional information: Object reference not set to an instance of an object.

And the error cursor was pointing to the line SMPSdata.LIV_(s)

How should I fix this error?

Upvotes: 2

Views: 44

Answers (2)

user3391202
user3391202

Reputation:

You should have initiate it before using the object, therefor you can use

Me.SMPSdata = New LIVandOSA()
...

to create a new object

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460288

The error is self-explanatory, you haven't initialized that object.

Since you are in the constructor it is a good place to initialize fields and properties:

Class TestUnitID
    Public SMPSdata As LIVandOSA
    Public SMdata As LIVandOSA
    Public COATEDBARdata As LIVandOSA
    Public CLCLdata As LIVandOSA

    Public Sub New(ByVal s As String)
        Me.SMPSdata = New LIVandOSA()
        Me.SMdata = New LIVandOSA()
        Me.COATEDBARdata = New LIVandOSA()
        Me.CLCLdata = New LIVandOSA()

        SMPSdata.LIV_(s)
    End Sub
End Class

Upvotes: 2

Related Questions