Calling Default Constructor from Parameterized Constructor

Alex picture Alex · Dec 2, 2009 · Viewed 13.9k times · Source

I would like my default constructor to create & initialize all the objects shown in my code snippet. Then I would like my parameterized constructor to call the default constructor, thus creating and initializing those objects, that can then be used in the parameratized constructor without getting a NullReferenceException.

In this situation, I'm not really sure what the best (most efficient, less code, etc.) way to use constructors is. I'd prefer to use constructor chaining.

Again, I have a very elementary understanding of constructors, so if this is not possible, then please just tell me so, and tell me what you would do in this situation.

class Rectangle
{
    public Line left { get; set; }
    public Line top { get; set; }
    public Line right { get; set; }
    public Line bottom { get; set; }

    public Rectangle() : this(new Line()) { }

    public Rectangle(Line diagnonal) 
    {
        left = new Line();
        top = new Line();
        right = new Line();
        bottom = new Line();

        Point beginningDiagonalPoint = new Point();
        Point endingDiagonalPoint = new Point();

        beginningDiagonalPoint = diagnonal.startPoint;
        endingDiagonalPoint = diagnonal.endPoint;

        int begXC = beginningDiagonalPoint.xCoord;
        int begYC = beginningDiagonalPoint.yCoord;

        int endXC = endingDiagonalPoint.xCoord;
        int endYC = endingDiagonalPoint.yCoord;

        Point rightSideEnd = new Point();

        rightSideEnd.xCoord = endXC;
        rightSideEnd.yCoord = begYC;

        Point leftSideEnd = new Point();

        leftSideEnd.xCoord = begXC;
        leftSideEnd.yCoord = endYC;

        // ----------- right side definitions -------------
        right.startPoint = endingDiagonalPoint;
        right.endPoint = rightSideEnd;

        // ------------ left side definitions --------------
        left.startPoint = beginningDiagonalPoint;
        left.endPoint = leftSideEnd;

        // ------------ top side definitions -------------
        top.startPoint = leftSideEnd;
        top.endPoint = endingDiagonalPoint;

        // ------------ bottom side definitions -----------
        bottom.startPoint = rightSideEnd;
        bottom.endPoint = beginningDiagonalPoint;
    }
}

Answer

CrispinH picture CrispinH · Feb 7, 2014

I just added

: this()

after the parametrized constructor. It was a bit of guess, but it seems to work.