C# C# Objects Inheritance Inheritance

Fatemeh Saryazdi
Fatemeh Saryazdi
5,369 Points

I have difficulty with getting my code compiled for Polygon and Square class. Can you please provide the solution?

Seems like the sub-class Square has the attribute "SideLength" that the base class doesn't have that. How I can use constructor in this case?

Polygon.cs
namespace Treehouse.CodeChallenges
{
    class Polygon
    {
        public readonly int NumSides;

        public Polygon(int numSides)
        {
            NumSides = numSides;
        }
    }

    class Square : Polygon 
    {
        public readonly int SideLength 

        public Square (int NumSides, int sideLength): base (4)
        {
            SideLength = sideLength;
        }        
    }
}
Fatemeh Saryazdi
Fatemeh Saryazdi
5,369 Points

Thanks Andren. I figured it our soon after posting the discussion. Thanks anyways!

1 Answer

andren
andren
28,390 Points

The are two issues with your code:

  1. You have forgotten a semicolon after the sideLength declaration.
  2. The constructor for the Square class does not need to have a parameter for the number of sides. A Square will always have 4 sides (that's a pretty fundamental part of being a square) so having to pass it in as an argument is pointless.

If you fix those two issues like this:

namespace Treehouse.CodeChallenges
{
    class Polygon
    {
        public readonly int NumSides;

        public Polygon(int numSides)
        {
            NumSides = numSides;
        }
    }

    class Square : Polygon 
    {
        public readonly int SideLength;

        public Square (int sideLength): base (4)
        {
            SideLength = sideLength;
        }        
    }
}

Then your code will work.

The fact that the Square has an attribute that the Polygon does not have is not really an issue, as the constructor of an inherited class is independant of its parent constructor in terms of what parameter you do or do not include. The only requirement is that you initialize the parent class by passing in arguments to its constructor in the base call. Which you are doing correctly in your code.