List as a property

Pirahnaplant

Well-known member
Joined
Mar 29, 2009
Messages
75
Programming Experience
3-5
I have a class with a property that is a list. Within the Set portion of the property I want to run some code, however the problem is that the code is not executed when the list is modified with something such as List.Add, List.Remove, etc. Is there something I can do about this?
 
When you call Add or Remove on the List you aren't executing the property setter. You're executing the property getter. The property value is the List. You are getting the List and then calling a method on that. At no point are you setting the property value by assigning a new List object to it. In fact, your property shouldn't even have a setter. It should be ReadOnly.

If you want to execute code when you add and remove items then you shouldn't be using a List. You should be defining your own class that inherits Collection(Of T) and then you can add your own functionality. You can add events that get raised when the collection changes and your class that exposes the collection via the property can handle those events.

Alternatively, you could use the BindingList(Of T), which already inherits Collection(Of T) and adds a ListChanged event. If that's all you need then it's already done for you. If you need more then you have to do it yourself.
 
Your class should look something like this:
VB.NET:
Public Class SomeClass

    Private WithEvents _objects As BindingList(Of Object)

    Public ReadOnly Property Objects() As BindingList(Of Object)
        Get
            Return Me._objects
        End Get
    End Property

    Private Sub _objects_ListChanged(ByVal sender As Object, _
                                     ByVal e As ListChangedEventArgs) Handles _objects.ListChanged
        Select Case e.ListChangedType
            Case ListChangedType.ItemAdded
                '...
            Case ListChangedType.ItemDeleted
                '...
        End Select
    End Sub

End Class
 
Back
Top