enforce event calling on inherited classes

M

Matt F.

I have an abstract class that about a dozen sub-classes inherit from. I
want to enforce that each sub-class shadows an event in the abstract class,
but can't quite figure out how to do this.

Basically, all of the inherited classes deal with data in some way or
another. I need to make sure that when the data is changed on any of those
classes, they raise an event called "DataChanged", and have that enforced in
some way from the abstract class.

I've tried a number of approaches, including "MustOverride Event", which
apparently isn't allowed. Also, I've created an interface with just the
DataChanged event, but there doesn't appear to be any sort of "Must
Implement" available --- to make matters worse, when trying to raise an
event from the inherited class on the abstract class, that doesn't appear to
be allowed either.

Obviously I can create an interface and just "remember" that every one of
the sub-classes must implement this interface, but that's error prone and
relies on me remembering additional steps, which obviously isn't a good
idea.

Any suggestions?
 
G

Guest

Hi Matt,
One possibility. Have the base class event handler delegate (call) a
mustoverride sub.
 
G

GhostInAK

Hello Matt F.,

It's quite simple really. I chose to model a predatory animal for my example..
but the principles are there for your data manipulation classes.
Define your event in an interface:

Public Interface IPredator

Event Eatten()

End Interface



Then create an abstract base class from which all others will inherit, which
implements the interface:

Public MustInherit Class Predator
Implements IPredator



Public Event Eatten(ByVal tSender As Object, ByVal tEatten As Object) Implements
IPredator.Eatten


Public Overridable Sub Eat()

RaiseEvent Eatten()

End Sub

End Class

Notice the Eat() sub. It's sole job is to raise the Eatten event on our
abstract class.



Now create a subclass of our base class:

Public Class Tiger
Inherits Predator



Public Overrides Sub Eat()

MsgBox("Yummie")
MyBase.Eat()

End Sub

End Class



Here you see that the Eat() sub overrides the base implementation. The last
thing we do here is call the base class's Eat() method, which will raise
the Eatten event.

The eatten event is available on the subclass like so:

Dim tTiger as Tiger = New Tiger
AddHandler tTiger.Eatten, AddressOf some_event_handler


Enjoy.

-Boo
 
M

Matt

Thank you for such a well written answer and fully qualified code. It gets
me 95% of the way there, and now I just need to make sure that I do call the
DataChanged event at the property time.
 

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