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()
{
    .............
}

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.


Yes, the base class constructor will be called automatically. You do not need to add an explicit call to base() when there is a constructor with no arguments.

You can easily test this by printing out the age of the customer after construction (link to ideone with a demo).


If you did not have a default parameterless constructor then there would be a need to call the one with parameters:

class Person
{
    public Person(string random)
    {

    }
}

class Customer : Person
{
    public Customer(string random) : base (random)
    {

    }
}