Nested Properties

Doggo120

Newcomer
Joined
Oct 7, 2011
Location
Colombia
Hey guys!

I'm using VB.net and I would want to have "property properties" of a class like this:

Thing.Property1 = "Yo!" (*1)
Thing.Property1.AnotherThing = 0
Thing.Property1.AnotherThing2 = True

I understand I can use 'property Property1 as class' but if I do that, Property1 must get or set a Class, not a variable (*1) which is what I want. The contextualized example would be something like this:

Music.Note = 32 (A number representing a musical note)
Music.Note.MIDINumber (Retrieve the MIDINumber of Note)
Music.Note.Name (Retrieve the name of Note)

You can see it in this case:
Textbox1.Text="Something"
Textbox1.Text.Length

...Well, thanks for your help! :D
 
Last edited:

snarfblam

Ultimate Contributor
Joined
Jun 10, 2003
Location
USA
In your example, Textbox1.Text.Length, the Textbox1.Text property returns string, which provides it's own properties, such as Length.

You would have to do the same thing. You would need a Note class (or struct) that the property returns.
Code:
Public Structure Note
    Dim _Value As Integer

    Public Sub Note(value As Integer)
        _Value = value
    End Sub

    Public Readonly Property Value() As Integer
        Get
            Return _Value
        End Get
    End Property

    Public ReadOnly Property Name() As String
        Get
            Throw New NotImplementedException("Put some code here")
        End Get
    End Property

    Public ReadOnly Property MidiNumber() As Integer
        Get
            Throw New NotImplementedException("Put some code here")
        End Get
    End Property
End Structure
Now you can create the Note property in your Music class.
Code:
    Dim _Note As Note
    Public Property Note() As Note
        Get
            Return _Note
        End Get
        Set(ByVal value As Note)
            _Note = value
        End Set
    End Property
Then, you could access it like so.
Code:
Music.Note = New Note(32)
MessageBox.Show(Music.Note.MidiNumber.ToString())
MessageBox.Show(Music.Note.Name)
Notice that all the properties are declared "Readonly." When working with structures, it's a good idea to make them immutable (meaning the Note objects can't be changed, but you can assign a new Note object to the Music.Note property.) If your curious, here is an explanation of why structures should be immutable. Or, just make Note a class instead of a structure.
 
Top Bottom