I'm writing a C# game engine for my game, and I've hit a problem.
I need to do a XNA.Rectangle drawRectangle for each different type of block.
Blocks are stored in a list of blocks, so the property, to be accessible by draw without casting a lot, must be overriden.
I've tried lots of ways of doing it, but none work.
Here's the current one I'm doing:
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 0, 0, 32, 32.
Ideally I could just override the drawRectangle
member, however doing this would mean creating a member in every single block class. I only want to adjust m_drawRectangle.
Each block will be created hundreds of times so I don't want it to be non-static, and it would be silly to do it in the constructor.
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
, onlym_drawRectangle
. - Not having to create a new rectangle every time the property is accessed
You don't have to override drawRectangle in each class if you use the virtual keyword.
Block.cs
BlockX.cs
As others as mentioned that you cannot override a static member, but i would like to improvise on the answer keeping in consideration any issues which may arise during static member creation or due to application pool recycle or similar events.
You can't override a static member.
I realize you do not want to override drawRectangle, but that appears to be the simplest solution to implement given what you have in your question. Your best solution is to declare a new static field in each derived class and override the instance property to achieve the results you want:
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: