Angelo Badellino
Angelo Badellino

Reputation: 2191

Override List (Of).Add Behaviour

I hava a class with this public property

Private _tickets As List(Of Ticket)
Public Property Ticekts() As List(Of Ticket)
    Get
        Return _tickets
    End Get
    Set(ByVal value As List(Of Ticket))
        _tickets = value
    End Set
End Property

When I call the add method, I have to perform some logic BEFORE add the ticket.

The logic is not an important topic, but I eventually have to remove some ticket before ADD the new one.

How can I do that?

Upvotes: 2

Views: 3642

Answers (1)

Phil
Phil

Reputation: 42991

You need to derive your own collection as follows:

C# version:

public class MyList<T> : Collection<T>
{
    protected override void InsertItem(int index, T item)
    {
        // your checks here
        base.InsertItem(index, item);
    }
}

List<T> doesn't have virtual methods so you aren't able to override Add. Collection<T> has virtual InsertItem, SetItem, RemoveItem and ClearItems.

VB.NET version:

Public Class List(Of T) 
    Inherits Collection(Of T)

    Protected Overrides Sub InsertItem( index As Integer, item As T )
        'your checks here
        MyBase.InsertItem(index, item)
    End Sub

End Class

Upvotes: 9

Related Questions