wenLiangcan
wenLiangcan

Reputation: 109

How to reimplement an inheriting event handler?

public class A : Form
{
  buttonOK;
}
public class B : A
{
}

the click event of buttonOK in class A has a handler buttonOK_Click, I want to invalidate it in class B and add a new click event handler for buttonOK.

Can I just set the accessibility of buttonOK_Click in class A as protected and use new keyword to hide it in class B ?

Upvotes: 0

Views: 102

Answers (3)

user2473359
user2473359

Reputation: 51

Use "New" keyword will break the registration of button click event, thus your buttonOK_click in class B would not be executed. Two common practices are:

1 Declare buttonOK_client in base class as virtual and override it in derived class.

2 Introduce Validate virtual function in base class and provide different implementation in base and derived class:

 public class A : Form
 {
    void buttonOK(...)
    {
        if (Validate())
        {
            //...
        }
    }

    virtual bool Validate()
    {
        //...
    }
 }
 public class B : A
 {
    override bool Validate()
    {
        //...
    }
 }

Upvotes: 3

jacob aloysious
jacob aloysious

Reputation: 2597

Agree with John, making the button Click event virtual should be the best option.

Here is an example..

public partial class Base : Form
{
    public Base()
    {
        InitializeComponent();
    }

    protected virtual void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("From Base");
    }
}

public class Derived: Base
{
    protected override void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("From Derived");
    }
}

Upvotes: 1

John Saunders
John Saunders

Reputation: 161773

A derived class can't just "reach into" a base class and change the implementation. The best you can do is to make the event handler virtual in the base class, then you can override it in the derived class.

Upvotes: 4

Related Questions