Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force child class to initialize fields

Tags:

c#

oop

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
}
like image 425
edeboursetty Avatar asked Aug 15 '12 14:08

edeboursetty


1 Answers

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;
    }
}
like image 51
Jon Skeet Avatar answered Oct 06 '22 01:10

Jon Skeet