Ivan Li Ivan Li - 4 months ago 37
C# Question

Will the base class constructor be automatically called?

class Person
{
public int age;
public Person()
{
age = 1;
}
}

class Customer : Person
{
public Customer()
{
age += 1;
}
}

Customer customer = new Customer();


Would the age of customer be 2? It seems like the base class's constructor will be called no matter what. If so, why do we need to call
base
at the end sometimes?

public Customer() : base()
{
.............
}


I'm C# newbie, thanks for your help

///////////////////////////////////////////////////////////////////////////////////////////

Thanks for Tejs's help,
now I understand that

if sub-class has constructor, the constructor must call one of base class's constructors first then perform itself (normally calling default constructor).

In this case, if base class contains constructors with parameter, sub-class's constructor needs to clarify which constructor is it calling (default or others)...therefore, base() or base(parameter......) would be needed.

Pleased to point out if I have misinterpreted.

Answer

This is simply how C# is going to work. The constructors for each type in the type hierarchy will be called in the order of Most Base -> Most Derived.

So in your particular instance, it calls Person(), and then Customer() in the constructor orders. The reason why you need to sometimes use the base constructor is when the constructors below the current type need additional parameters. For example:

public class Base
{
     public int SomeNumber { get; set; }

     public Base(int someNumber)
     {
         SomeNumber = someNumber;
     }
}

public class AlwaysThreeDerived : Base
{
    public AlwaysThreeDerived()
       : base(3)
    {
    }
}

In order to construct an AlwaysThreeDerived object, it has a parameterless constructor. However, the Base type does not. So in order to create a parametersless constructor, you need to provide an argument to the base constuctor, which you can do with the base implementation.