I have abstract base class that contains some fields and some methods that act on these fields. For example:
public abstract class A
{
protected double _field;
public double SquaredField { get { return _field * _field; } }
... some other abstract methods
}
I want to impose that all children of A initialize _field in their constructors
public class B : A
{
public B(double field)
{
_field = Math.Sqrt(field);
}
... some other method implementations
}
What's the correct pattern to achieve this?
-- EDIT
What I ended up doing is:
public abstract class A
{
protected readonly double _field;
public A(double field)
{
_field = field;
}
public double SquaredField { get { return _field * _field; } }
... some other abstract methods
}
public class B : A
{
public B(double field) : base(field)
{
}
public static B CreateNew(double val)
{
return new B(Math.Sqrt(field));
}
... some other method implementations
}
Don't expose a field to the derived classes at all. Instead, create a protected abstract property:
public abstract class A
{
protected double Field { get; }
public double SquaredField { get { return Field * Field; } }
}
Or, if the field should always be constant for a particular instance, make it a constructor parameter and keep it private:
public abstract class A
{
private readonly double _field;
public double SquaredField { get { return _field * _field; } }
protected A(double field)
{
_field = field;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With