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 setmodifier, then allows the child class more power than I'm asking for. initisn't an option because I only want it set in the constructor.readonlywon'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;
}
}
To achieve this, you can give the base class a constructor, you can make it
protectedif you like:And your old can call the base class constructor, for example:
Or if you want to pass in a constant value as per your example: