I know that when inheriting classes, you can also inherit Constructors
example:
class Book : Genre
{
Book(string param1, int param2, string inherit1, string inherit2) : Base(inherit1,inherit2)
{
Prop1 = param1
Prop2 = param2
}
}
But wouldn’t it just be easier to set the inherited properties via the constructor in the inherited class. Instead of referencing the base constructor?
class Book : Genre
{
Book(string param1, int param2, string inherit1, string inherit2)
{
Prop1 = param1
Prop2 = param2
InhProp3 = inherit1
InhProp4 = inherit2
}
}
It is different, though. Setting the property does not have the same behavior.
When you use a base class constructor which takes parameters, the base class has the ability to set those properties, and potentially have customized behavior based on those parameters, that runs prior to the subclass constructor.
If you set the property manually in the subclass constructor, the base class constructor has already run. This may change the behavior – sometimes significantly (especially if the base class is poorly designed).
Also, if the base class requires that information in order to construct itself, you have no choice. Often, constructor parameters do more than just setting a property of the class – they can be critical to the construction of the object itself.