Search code examples
c#overridingabstract-classtype-inferenceabstract-data-type

Inheriting abstract classes with abstract properties


I have base class with abstract properties. I want all inheriting classes to override abstract properties. Example:

public class Person
{
    public string Name{get;set;}
    public string LastName{get;set;}
}

public class Employee : Person
{
    public string WorkPhone{get;set;}
}

public abstract class MyBase
{
    public abstract Person Someone {get;set;}
}

public class TestClass : MyBase
{
    public override Employee Someone{get;set;} //this is not working
}

Base class has Someone property with Person type. I am overriding Someone property on my TestClass. Now I want to use Employee type instead of Person. My Employee class inherits from Person. I couldn't make it work. What should I do to avoid this problem?

Help appreciated!


Solution

  • The problem is that you may be able to assign an Employee to a Person instance, but you can't also assign a Person to Employee instance. Therefore, your setter would break. You either need to get rid of the setter, or use a private backing instance and some casting (which I wouldn't recommend) which would look like:

    public class TestClass : MyBase
    {
        private Employee _employee;
    
        public Person Someone
        {
            get
            {
                return _employee;
            }
            set
            {
                if(!(value is Employee)) throw new ArgumentException();
                _employee = value as Employee;
            }
    }