Overriding a class base event when inheriting from that class?

B

Brian Mitchell

Below is a sample code of what I am trying to do. I have a class that
inherits from ArrayList and I need to override the Add method. However,
Overloads and Shadows are the only approaches I can seem to take.

I need to override the add method because I want to ensure the passed object
is only of a specific type. The question is, if I shadow the add method then
what do I use for the implementation of the sub? If I call me.Add I end up
in a loop.



In the example, if I use overloads (instead of overrides) the add method
will take either my Customer as Customer object or simply Value as Object
(from the base class). I need to eliminate the Value as Object and only have
it accept Customer as Customer.

Confused yet?

Here is my example:

Public Class Customers

Inherits ArrayList

Public Shadows Sub Add(ByVal Customer As Customer)
---How do I add Customer to the actual Customers ArrayList?

End Sub





Public Class Customer
....
....
....
Some properties here
....
....
....

End Class

End Class



btw, I know that I can simply declare a private variable as an ArrayList in
the Customers class and I would be able to make my own methods for it, but
in my program the class uses some implements and must inherit from the
ArrayList and I need to pass the entire class back as an ArrayList so I am
in a pickle.

Thanks for the help!!
 
S

Scott

Try something like this...

Public Overrides Function Add(ByVal value As Object) As Integer
If value.GetType.Name = "Customer" Then
Return MyBase.Add(value)
Else
Return -1
End If
End Function
 
J

Jay B. Harlow [MVP - Outlook]

Brian,
Rather then attempting to Inherit from ArrayList, I would recommend you
inherit from System.Collections.CollectionBase.

Then add the type safe methods you need:

Public Class CustomerCollection
Inherits Collection Base

Public Sub Add(ByVal customer As Customer)
InnerList.Add(customer)
End Sub

Public Sub Remove(ByVal customer As Customer)
InnerList.Remove(customer)
End Sub

Default Public Readonly Property Item(ByVal index As Integer) As
Customer
Get
Return DirectCast(InnerList(index), Customer)
End Get
End Property

End Class

CollectionBase gives you much greater control over your class; for example:
the add method only accepts a Customer so you get a compiler time error
instead of a runtime error.

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top