Event handling question

H

hillcountry74

Hi,

I'm a newbie and trying to understand event handling in c#. I have
understood handling events using delelgate objects. But not this
method- "Event handling by overriding the virtual protected method of
the base class". Can someone please explain this with a sample code?

Thanks a lot.
 
N

Nicholas Paldino [.NET/C# MVP]

This is not really accurate. For classes that fire events, (such as the
Button class with the Click event), there is usually a method (named
On<Event>, in this case, OnClick) that is called to fire the events. This
method is usually marked as virtual, so that it can be overriden by classes
that derive from it. It is easier to put some specific logic in here than
attach a delegate to yourself (and it's quicker as well).

Usually, you will see this in classes overriding controls to paint
themselves, so they will override OnPaint.

Hope this helps.
 
H

hillcountry74

I'm from a VB background and I guess this is not making it clear for me
to understand. What I'm still missing is that if the derived class adds
some code in the OnClick method, the base class' method must still be
called, ie base.OnClick..

In the OnClick method of the base class, the event is raised. But in
the derived class's OnClick method you are not exactlly handling the
event right? You are still raising the event. I've read in a few
articles and a book wherein they state that the derived class is
handling the event by overriding the base class method. This is still
not clear to me...

Please explain.

Thanks for your help.
 
N

Nicholas Paldino [.NET/C# MVP]

Basically, when a button is clicked, the OnClick method is called to
fire the event. Now, because you are deriving from Button, you can place
some extra code in here before or after (or both) the event is fired (by
calling the base implementation) to implement some specific logic to your
class (whatever you wish it to be). This is handling the click event still,
but is only possible for those classes that offer this kind of method that
performs the default action.
 

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