Search code examples
c#.netinheritancepolymorphismvirtual

Override property or calculate property in constructor


For example I have base class and I need a property that will be calculated in derived classes.I have two variant (SomeProperty1 and SomeProperty2):

public class BaseClass
{
    public int SomeProperty1{get;set;}
    public override int SomeProperty2{get;set;}
}

public class DerivedClass : BaseClass
{
    public DerivedClass()
    {
       SomeProperty1 = 100;
    }
    public override int SomeProperty2
    {
        get
        {
            return 100;
        }
    }
}

The questions is what is the best way, SomeProperty1 or SomeProperty2?


Solution

  • Add to the base class a protected abstract method called CalcSomeProperty().

    Then implement your property in terms of CalcSomeProperty(). That will force the derived classes to implement it.

    For example:

    public abstract class BaseClass
    {
        public int SomeProperty
        {
            get
            {
                return CalcSomeProperty();
            }
        }
    
        protected abstract int CalcSomeProperty();
    }
    

    Alternatively, you can make the property itself abstract:

    public abstract class BaseClass
    {
        public abstract int SomeProperty { get; }
    }
    

    In either case, you are forcing derived classes to implement the property calculation.

    An advantage of separating the calculation into a protected method (rather than using the simpler abstract property) is that you can perform caching in the concrete property implementation if the calculation is slow:

    public abstract class BaseClass
    {
        protected BaseClass()
        {
            _someProperty = new Lazy<int>(CalcSomeProperty);
        }
    
        public int SomeProperty
        {
            get
            {
                return _someProperty.Value;
            }
        }
    
        protected abstract int CalcSomeProperty();
    
        private readonly Lazy<int> _someProperty;
    }