Property of a Property of an Object

tora

New member
Joined
Dec 22, 2010
Messages
2
Programming Experience
10+
Hello, I'm posting in hopes of someone being able to help me figure out what I'm doing wrong in the following code
VB.NET:
Public Class HouseAddress
    Public Property HouseNumber As Integer
    Public Property StreetName As String

    Private Sub Init()
        HouseNumber = 0
        StreetName = "TEST ST"
    End Sub
End Class
VB.NET:
Public Class Person
    Public Property Name As String
    Public Property Location As HouseAddress

    Private Sub Init()
        Name = "Test Name"
        Location = new HouseAddress()
    End Sub
End Class
and within the main app:
VB.NET:
Class Window1
    Dim Tora as Person

    Private Sub Init()
        Tora = new Person()
        Debug.WriteLine(Tora.Name)
        Try
            Debug.WriteLine(Tora.Location.StreetName)
        Catch ex As Exception
            Debug.WriteLine("Error=" + ex.Message)
        End Try
    End Sub
End Class

And the output I'm getting is:
"Test Name"
"Error=Object reference not set to an instance of an object"

I understand the error is saying I've got a null pointer reference happening, but I don't understand why. Anyone smarter than me able to help?

Thanks a lot!!
 
In your last code snippet, you create a Person object but you never call its Init method, so a HouseAddress object is never created or assigned to its Location property. I think maybe you are under the misconception that your Init methods are constructors. They aren't. A constructor is always named New. Change the name of the Init method in the Person class to New and it will be invoked automatically when you create a New Person.
 
Holy Smokes! Thank you. You were exactly right, I thought the Init() methods were the constructors, changed to New() and all is right with the world. Thanks a lot!
 
Back
Top