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

I do not understand the : base part. What is it doing?

I really do not understand what happens when you've created the Square base class (derived from Polygon) and then thereafter you state parameter but followed by : and the word 'base'.

Please can someone explain this to me using examples other than squares/polygons?

Thank you

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

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

1 Answer

Steven Parker
Steven Parker
230,995 Points

:point_right: base refers to the parent class that the current one inherits from.

A derived class constructor always calls its parent class constructor first. Typically, there is no special syntax and the parent's default constructor is used.

In cases where the parent has no default constructor, or where an alternative constructor is desired, the ": base()" syntax can be used to specify the argument(s) to be passed to the alternative parent constructor.

Thanks :)

Would it be possible to perhaps give an example of a child class calling a base class constructor? But something other than Square/Polygon. It would be helpful for me to see it used in another way. Something simple.

Thank you