views:

84

answers:

5

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
    }
}
+4  A: 

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.

Reed Copsey
+3  A: 

If your base class at some point in time has been redesigned to do something more complex than just setting members, then you will be happy to have called it.

If not you will look for an error, find it after maybe hours of debugging. And then you will never forget to delegate the call to the constructor of the base class again :-)

jdehaan
+1  A: 

The base class may do more than just setting properties. The base class could be a class that you don't have the source code to so you don't even know what it does with it.

Davy8
+1  A: 

The base constructor might be doing more than just setting properties, it might for example check for null references. If you would do that in the inheriting class, then you would need to repeat all the code. Then you would have the same code in two places, so if the code ever had to change, you would have to know that it needed changing in both places.

Guffa
+1  A: 

Depends on how the class is designed.

Perhaps the properties are public get; private set; In which case, your derived class doesn't have access to set the properties.

Also, iirc, calling a constructor to set parameters, generates less IL than setting the values in the body of your constructor.

Alan