Calling a parent class method

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a class (sharedClass) that is instantiated (not derived) by two other
classes (guiClassA and guiClassB). The sharedClass needs to be able to call
a method that is defined in its parent class (guiClass).

Specifically, when guiClassA or guiClassB calls a method from the
sharedClass, the sharedClass needs to log its actions by sending strings to
the guiClass (via guiClass method calls), which in turn display or record
this log information in their own unique ways.

How can the sharedClass call out a function from its parent class without
knowing exactly what kind of class the parent class is? (I can however
guarantee that the parent class will implement the logging function).


Since both guiClasses are not used in the same application, I was able to
solve this in C++ by declaring the logging function prototype in a header
file that was included by all the classes, and then defining the function
implementation at the same level as the guiClass was instantiated. Thus, the
connection was made by the linker. Is there any way to do something similar
in C#?
 
I was going to suggest declaring the logging function(s) as an
interface implemented by both gui classes, but I just thought of a
better way.

Don't use methods at all. Use events. Have your sharedClass expose a
(or multiple) shared event(s). You can declare your own event arguments
and your own event handler type to carry any specialized information
you need. Whenever it needs to log anything, the sharedClass simply
raises the appropriate event.

It's then up to the enclosing guiClass to subscribe to the event(s) and
do whatever it needs to do (log the event) as appropriate.

I wouldn't even name the event according to what has to happen (don't
call it LogXXXX). Instead, I would name the event according to what
happened that was "loggable". You know: ValueChanged,
CertificateExpired, whatever. This may lead to multiple events from the
sharedClass, but this also achieves maximum decoupling, both logically
and conceptually. The sharedClass just notifies the "outside world"
when certain things happen and provides details about the event. The
guiClass is then just one interested party that happens to respond to
those events by logging them. Other classes may want to subscribe to
the events for other reasons.

So... I would use a completely different paradigm: events rather than
callbacks.
 

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

Back
Top