If the base class and derived class both have their constructors with parameters then where we pass the parameters to the base class constructors?
Passing parameters to the base class constructor
Asked Answered
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.
Is the default constructor still invoked if base constructor is called as
:base(param)
? –
Piperidine No. That constructor would have to call
this()
@Ahmn21 –
Minervamines public class DerivedClass(object param): BaseClass(param){// in .net core 8}
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.
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 thebase
keyword with the derived constructors. – Departed