Search code examples
c#propertiesabstract-classaccess-modifiers

Make property in abstract class only settable in constructor of child class?


I have a get-only property in a concrete class. By definition, that can only be set in a constructor of that class. I later decide that I want this property to belong to a constructor-less abstract class that the concrete class inherits from. How can I make the property that is now in the abstract class only capable of being set within the constructors of the child classes?

Solutions that won't work:

  • If I give the property a protected set modifier, then allows the child class more power than I'm asking for.
  • init isn't an option because I only want it set in the constructor.
  • readonly won't always work, because I'm on C# 7.3.

Example original class:

public class FooOriginal
{
   public int IntHere { get; }
}

Example abstract class:

public abstract class FooAbstract
{
   public int IntHere { get; }
}

Example child class

public class FooChild : FooAbstract
{
   public FooChild()
   {
       // Won't compile because IntHere is get-only.
       intHere = 3;
   }
}

Solution

  • To achieve this, you can give the base class a constructor, you can make it protected if you like:

    public abstract class FooAbstract
    {
        public int IntHere { get; }
    
        protected FooAbstract(int intHere)
        {
            IntHere = intHere;
        }
    }
    

    And your old can call the base class constructor, for example:

    public class FooOriginal : FooAbstract
    {
        public FooOriginal(int intHere)
            : base(intHere) // <-- This is the magic
        {
            
        }
    }
    

    Or if you want to pass in a constant value as per your example:

    public FooOriginal() : base(3)
    {
    }