Luka Horvat
Luka Horvat

Reputation: 4412

Executing code after all the overrides of a virtual method

So I have this system set up with a base class DisplayObject. It has a Render method and a list of other DisplayObjects as it's children. It also contains data about various matrix transformations but I does not contain the data about the actual drawing. That's why the Render method is virtual.

I then have 2 classes. ColoredShape and TexturedShape each inheriting from DisplayObject and overriding the Render method with a new method starting with

base.Render(); 

and then doing the drawing code.

What I want now is to call Render on all of the object's children after the Render on the parent has finished. So there's my problem. If I do

foreach (var child in Children) child.Render();

at the end of the Render method in the DisplayObject class it will be executed before the overrides are, since it's a part of the base.Render() call, and if I put that code in the subclasses instead, the DisplayObject alone loses that functionality and it forces all the future subclasses inheriting from it to implement the feature manually.

Upvotes: 2

Views: 438

Answers (2)

s1mm0t
s1mm0t

Reputation: 6095

What you want is the abstract method pattern. In other words, don't make your render method virtual crate another method (virtual or abstract) that render calls., so render will look something like this:

public void Render()
{
    DoRender()

    foreach (var child in _children)
    {
        child.Render();
    }
}

protected virtual void DoRender()
{
}

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1063609

Split the code so the "render self" is separate from "render children":

public void Render() {
    OnRender();
    foreach(var child in Children) child.Render();
}
protected abstract void OnRender();

The subclasses provide OnRender, which renders self, but not the children. That is handled by Render. In some cases it may be useful to make Render as virtual so that the subclasses can control this if they need different child-behaviour.

Upvotes: 1

Related Questions