Search code examples
c#inheritanceclass-structure

How to force derived class to implement a static property or field?


This is my abstract class:

abstract class Enemy
{
    protected static abstract float HEALTH
    {
        get;
    }

    float health;

    void someMethod()
    {
        health = HEALTH;
    }
}

This is my derived class:

abstract class BadGuy : Enemy
{
    protected override static float HEALTH
    {
        get { return 1; }
    }
}

Mr. Compiler says I can't make the member HEALTH static as well as abstract in the Enemy class.

My goal is to force each child class to have a static or constant field which can be accessed from the parent class.

Is there a solution for this? If not, what's the most elegant workaround? Making the property non-static?


Solution

  • static and inheritance don't work together. What you can do is make a virtual property which can be overridden in the derived class. If you wish, you can either provide a base implementation inside Enemy, or keep it abstract if you don't want to:

    public abstract class Enemy
    {
        protected abstract float Health { get; }
    }
    
    public class BadGuy : Enemy
    {
        private const int BadGuyHealth = 1;
        protected override float Health
        {
            get { return BadGuyHealth; }
        }
    }
    
    public class EvenWorseGuy : BadGuy
    {
        private const int WorseGuyHealth = 2;
        protected override float Health
        {
            get { return WorseGuyHealth; }
        }
    }