Fire events selectively in C #

class Child
{ 
    private override void Check_CheckedChanged(object sender, EventArgs e)
    {
        if (Check.Checked)
        {
            this.addName(this.FirstName);
            this.disableControls();
        }

        else
        {
            this.addAddress(this.address);
            //this.activatecontrols();// gives error since it private method in parent.

        }
    }
}

class Parent
{
    private  void Check_CheckedChanged(object sender, EventArgs e)
    {
        if (Check.Checked)
        {
            this.disablecontrols();
        }

        else
        {
            this.addAddress(this.address);
            this.activatecontrols();
        }
    }

}

      

I want to fire a child event if it meets the condition. But if I don't need to call the else condition, since I have activated controlcontrols (), it is private in Parent. So how can I name the event?

+1


source to share


2 answers


If you need functionality ActivateControls

in a derived class, you can do it protected

in a base class.

Alternatively, you can handle the event handler with a Check_CheckedChanged

method virtual

in the base class, which can be overridden in a derived class:

// Parent.cs

private void Check_CheckedChanged(object sender, EventArgs e)
{
    OnCheckedChanged();
}

protected virtual void OnCheckedChanged()
{
    if (Check.Checked)
    {
        this.disablecontrols();
    }
    else
    {
        this.addAddress(this.address);
        this.activatecontrols();
    }
}

      



The logic for Parent

doesn't need to be repeated in Child

order for the handler to be simplified:

// Child.cs

protected override void OnCheckedChanged()
{
    if (Check.Checked)
    {
        this.addName(this.FirstName);
    }

    base.OnCheckedChanged();  // Same outcome
}

      

+3


source


A very simple solution would be to make ActivateControls a protected virtual in the Parent and override it in the child, then you can call base.activatecontrols in the child method if not Check.Checked.



+2


source







All Articles