Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

Emmet Lowry
Emmet Lowry
10,196 Points

Problem with inheritance Task

My code seems fine but not passing any advice im stuck for ages namespace Treehouse.CodeChallenges { class Polygon { public readonly int NumSides;

    public Polygon(int numSides) : base(4);
    {
        NumSides = numSides;
    }
class Square : Polygon
{
    public readonly int SideLength;
    public Square(int sideLength) 
    {
        SideLength = sideLength; 
    }
}

} }

3 Answers

akak
akak
29,445 Points

Hi,

You should use base on a constructor of derived class:

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; 
        }
    }
}

What is the purpose of the 'base' part? And what does he number 4 to do it? How does it then relate to the sideLength parameter?

Thank you :)

akak
akak
29,445 Points

By using base you are calling the constructor of the class you're inheriting from (in that case Polygon) with 4 as number of sides.. So let's try instantiate Square:

public Square mySquare = new Square(25);

After that your mySquare object will have

  • SideLength = 25 (because you explicitly set that in line above)
  • NumSides = 4 (because you've set that by doing base(4))

So you can think of base(4) as being a call to Polygon (the parent) like new Polygon(4) but not explicitly. It's done while constructing a new Square. That's the beauty of inheritance. You hardcoded that if you create Square it always a Polygon with 4 sides. User just have to enter length of side. I hope you get the gist :)

Why not to add triangle? It will be a polygon with 3 sides this time

    class Triangle : Polygon
    {
       public readonly int SideLength;

       public Triangle(int sideLength) : base(3) 
        {
            SideLength = sideLength; 
        }
    }
akak
akak
29,445 Points

You have to use base. If you won't you'll get:

error CS1525: Unexpected symbol `Polygon', expecting `base' or `this'.
Emmet Lowry
Emmet Lowry
10,196 Points

why is sidelength = SideLength