Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Default Constructor from Parameterized Constructor

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;
    }
}
like image 832
Alex Avatar asked Dec 02 '09 04:12

Alex


1 Answers

I just added

: this()

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

like image 154
CrispinH Avatar answered Sep 30 '22 03:09

CrispinH