Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The use of :base() in a constructor [duplicate]

Tags:

c#

inheritance

I am currently trying to construct an object which derives from a different object, but before calling the base constructor I would like to make a few argument validation.

public FuelMotorCycle(string owner) : base(owner)
{
    argumentValidation(owner);
}

Now I understood that initially the base constructor is called first, is there a way I can call it only after the argumentValidation method?

like image 455
Steinfeld Avatar asked Sep 07 '25 19:09

Steinfeld


1 Answers

The base constructor will be invoked first.

This example:

class Program
{
    static void Main(string[] args)
    {
        var dc = new DerivedClass();
        System.Console.Read();
    }
}

class BaseClass
{
    public BaseClass(){
        System.Console.WriteLine("base");
    }
}

class DerivedClass : BaseClass
{
    public DerivedClass()
        : base()
    {
        System.Console.WriteLine("derived");
    }
}

will output:

base
derived
like image 110
Thorkil Holm-Jacobsen Avatar answered Sep 10 '25 09:09

Thorkil Holm-Jacobsen