Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method and draw

Tags:

c#

winforms

I have 3 classes witch inherit another class called ParentClass and each of the 3 has the following code inside

public void DrawBackground(Graphics e, Rectangle rect)
{
    e.FillRectangle(Brushes.Red, rect);
}

In my main form i have a variable like this ParentClass PClass = new OneOfTheThreeClasses

How can i call the DrawBAckground method of those classes using that variable, from my form's paint event?

like image 276
Adrao Avatar asked May 10 '16 16:05

Adrao


1 Answers

Create either an abstract or virtual method on ParentClass. Something like this:

public virtual void DrawBackground(Graphics e, Rectangle rect)
{
    // do nothing
}

Then in the child classes, override that method:

public override void DrawBackground(Graphics e, Rectangle rect)
{
    e.FillRectangle(Brushes.Red, rect);
}

The idea is that ParentClass needs to define the operations which can be performed on it or any polymorphic version of it (such as a child type). It doesn't necessarily have to provide an implementation (and the definition can be abstract or virtual depending on how ParentClass itself is implemented and used), but does need to "know" about the method in some way in order for anything to be able to invoke it on an instance of ParentClass.

like image 175
David Avatar answered Nov 11 '22 09:11

David