New to OOP and I\'m confused by how derived-class constructors work when inheriting from a base class in C#.
First the base class:
class BaseClass
{
public SubClass(string BaseString, string SubString) : base(BaseString)
This constructor in the derived class says that when you receive two arguments BaseString
and SubString
, call the base class's constructor with BaseString
.
Thus, doing
public SubClass(string a, string b) : base(BaseString)
doesn't work, because you are telling it to call the base class's constructor with BaseString
but there is no argument called BaseString
.
If you want to instantiate the derived class without passing a String to the base class constructor, the base class needs a default constructor:
public BaseClass() { }
If you want to provide the opportunity for the derived class NOT to set the BaseString, then you need to provide a default constructor in the base class like this:
public BaseClass()
{
}
Now in the derived class, you can call the constructor with no arguments in the base class like this:
public SubClass(string AnotherString)
: base()
{
// base() => explicit call to default construct in the base class.
// Do something else
}
This provides good software engineering practice: if you want to provide the opportunity not to set the base class's string, then do so in the base class. Other 'hacks' like passing null as an argument to the base constructor only serve to tinker with the base class's internals in ways that should not be done from subclasses.
As to why you can't do:
public SubClass(string SubString) : base(BaseString)
What would BaseString
be?
You could do:
public SubClass(string SubString) : base("SomeFixedString")
or
public SubClass(string SubString) : base(SubString)
But if you want to pass one string to the base class constructor's parameter and have an additional one, you'll need to accept two parameters.
As to keeping the same name, you don't. You could do:
public SubClass(string AnotherString, string SubString) : base(AnotherString)
As to the last question, the first parameter isn't doing nothing, it's being passed to the base class constructor. You could use it for something else if you wanted to.
If you want to initialize BaseString
with default value, then pass that value to base class constructor (thus you don't have to pass that parameter to derived class constructor)
public SubClass(string SubString) : base(null)
Or define parameterless constructor in base class.
Also about parameter naming - it does not matter what name has parameter, which you are passing to derived constructor. The only thing which matter is a value you are passing to base constructor.
public SubClass(string AnotherString, string SubString) : base(AnotherString)