Search code examples
c#windowsstaticpolymorphism

Overriding static field


I'm writing a C# game engine for my game, and I wish to add a XNA.Rectangle drawRectangle for each different type of block.

Blocks are stored in a List<ParentType>, so the property must be overridden to be accessible by a central draw method.

I've attempted to do an approach with static fields:

Block.cs

protected static Rectangle m_drawRectangle = new Rectangle(0, 0, 32, 32);
public Rectangle drawRectangle
{
    get { return m_drawRectangle; }
}

BlockX.cs

protected static Rectangle m_drawRectangle = new Rectangle(32, 0, 32, 32);

However, when creating BlockX and accessing drawRectangle, it still returns a Rectangle(0, 0, 32, 32).

Ideally I would just override the drawRectangle member, but doing so would mean creating a new property for each block, when I only want to adjust m_drawRectangle. I'd also wish to avoid having a non-static field, as these classes are intended to be featherweight - each block will be instantiated hundreds of times.

Is there any better way other than just putting a static function to initialise static things in every block?

Edit:

So to sum up, my requirements are:

  • Minimal extra code in BlockX.cs to override
  • Field must stay static
  • Preferably not have to override drawRectangle, only m_drawRectangle.
  • Not having to create a new rectangle every time the property is accessed

Solution

  • Statics members aren't called polymorphically - it's as simple as that. Note that you talk about the property staying static - you don't have a static property at the moment. You have an instance property, and two static fields.

    A couple of options:

    • A virtual member which is overridden in each class, even though it doesn't need any state from the object other than its type
    • Pass the rectangle to draw into the constructor of the block, and store it in a field