Passing parameters to the base class constructor
Asked Answered
P

2

24

If the base class and derived class both have their constructors with parameters then where we pass the parameters to the base class constructors?

Proudfoot answered 5/5, 2014 at 20:40 Comment(3)
This is a duplicate question. #12551 Googling "base class constructor parameters" would have brought it right to you.Cicala
You say "you can't instantiate an abstract class," but that's not entirely true. If you create an instance of the non-abstract derived class, that instance is also an instance of the abstract base class. It is also an instance of the System.Object class.Myalgia
FYI, even if it's an abstract class, it can have defined custom constructors with parameters that can be passed in. They can't be instantiated/called directly but instead are referenced in derived types by using the base keyword with the derived constructors.Departed
M
63

Like this:

public class DerivedClass : BaseClass
{
    public DerivedClass(int derivedParam, String baseParam):base(baseParam)
    {
    }
}

The base keyword here calls the base class constructor that matches the provided parameter overload.

Minervamines answered 5/5, 2014 at 20:49 Comment(2)
Is the default constructor still invoked if base constructor is called as :base(param) ?Piperidine
No. That constructor would have to call this() @Ahmn21Minervamines
G
0
public class DerivedClass(object param): BaseClass(param){// in .net core 8}
Geopolitics answered 9/5 at 20:48 Comment(2)
Can you edit your answer to explain how this syntax is different from the original answer, and why .NET 8 permits this? That would benefit future readers.Dyslogistic
Notably, this assumes use of implicit constructors and variables, and so won’t be relevant to all scenarios. Calling that out is important for people unfamiliar with the assumptions baked into this syntax.Dyslogistic

© 2022 - 2024 — McMap. All rights reserved.