Search code examples
c#inheritancexnareturnradix

Returning in a base class's method returns in child class call?


I'm creating a C# framework in which (nearly) all of my classes will be based off of a single, abstract base class. This base class contains some privately-set properties, one of which being the boolean Garbage.

In XNA's draw loop, I don't want any child classes to execute the code in their respective Draw() methods if the base class's Garbage property is set to true. I tried doing this with the following implementation:

Abstract base class:

public virtual void Draw(GameTime GameTime, SpriteBatch SpriteBatch)
{
    if (Garbage) return;
}

Inherited class:

public void Draw(GameTime GameTime, SpriteBatch SpriteBatch, Color OverlayColor, float Scale)
{
    base.Draw(GameTime, SpriteBatch);

    //Other code here...
}    

Because the base class's Draw method is being called before the actual code in my child class, it hits that return statement, which I would want to follow through into my child class's Draw() call. However, this isn't happening.

Is there any way to achieve the effect I want, without adding that "if (Garbage) return;" restriction to the top of every inherited class's Draw() method?


Solution

  • One thing that you might consider is to have two methods. You could have your Draw method on the abstract base, which is not overridden, and then define an abstract protected method called PerformDraw() that your inheritors override.

    Abstract base draw looks like:

    public void Draw(GameTime GameTime, SpriteBatch SpriteBatch)
    {
        if (!Garbage) PerformDraw(GameTime, SpriteBatch);
    }
    

    This lets you override the draw behavior but forces all inheritors to use the "garbage" check.