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# C# Objects Inheritance Inheritance

Tim Heller
PLUS
Tim Heller
Courses Plus Student 7,729 Points

Inheritance Code Challenge

Can't seem to get passed errors on this Inheritance challenge. I would usually create a new file called Square.cs but it's a code module, not sure how to do that. Not sure if I'm missing a concept or simply not jumping through a hoop.

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

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

    class Square : Polygon
    {
        public readonly int SideLength;
        int numSides = 4;

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

2 Answers

Instead of creating a property, just initialize it by directly passing it in:

public Square(int sideLength) : base(4)
luke hammer
luke hammer
25,513 Points

you still need the read

public readonly int SideLength;
        int numSides = 4;
'''

you just can't use it in the base constructor.
luke hammer
luke hammer
25,513 Points

The variable numsides is not available until after the square is constructed.

Directly assign this value in your base constructor.

 public Square(int sideLength) : base(4)

new classes do not need to be in new files

Tim Heller
Tim Heller
Courses Plus Student 7,729 Points

Unexpectedly I get this error: "Did you create a public readonly integer field named SideLength in the Square class?" with the following code change.

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

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

class Square : Polygon
{
    public readyonly int SideLength;

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

}

luke hammer
luke hammer
25,513 Points

readonly

NOT

readyonly