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#

Is it required to pass the super class parameter for the subclass it is inheriting from?

So I haven been learning Java for a while but decided to switch to C#. It's been a while so I may forget some things. What I know is that in Java, when inheriting from a super class you can or can not call the super class and pass in the parameter if it accepts it. For example:

public class Super{
    public Super(int x)
    {
    }
}

public class Sub extends Super
{
    public Sub()
    {
        super(5);
    }
}

and then this other example:

public class Super
{
    public Super(int x)
    {
    }
}

public class Sub extends Super
{
    public Sub()
    {

    }
}

is also totally fine since it does not have to pass in parameter to the superclass, correct me if I am wrong. But then in C#, I am not sure if you are required to pass in the parameter for the superclass or not(like if it is still legal and won't cause any problem)

1 Answer

Steven Parker
Steven Parker
229,786 Points

In C#, you would pass the required parameter using a slightly dfferent syntax and the keyword "base": instead of "super".

But you're getting ahead of things, you'll see this discussed in the courses.

I am asking if it is required to call the base class. I know how to call the base class.

Steven Parker
Steven Parker
229,786 Points

It's required if the only constructor in the base requires an argument. It would be optional if the base class has overloaded constructors, one that takes an argument and one that does not.

So if the base constructor doesn't require an argument, do we put : base() or you can just omit that from the code. And also if the base class overloaded but all of them(constructor) required parameter then we must at call one constructor and pass in the argument, am I correct?

Steven Parker
Steven Parker
229,786 Points

You are correct, and you can omit the ": base(arg)" entirely when no argument is being passed.

Thank you so much for your help and clarifying. I am new learning C#, so syntax is a bit different from Java.