Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid calling the base class constructor

Tags:

c#

inheritance

I'm just after a little advice on how to best organise the inheritance here. I have a class (below) that needs to use most of, and overide some of, the classes in the base ExportData class:

public class ExtendedExportData : ExportData
{

    private tData _Data;
    private ResStrings _diaStrings;

    public ExtendedExportData(tData Data, ResStrings diaStrings)
        : base(tData, diaStrings)
    {
        _tData = Data;
        _diaStrings = diaStrings;

    }
}

What isn't neccesary in this case is having to call the base constructor as none of the base class methods used in the class above require that initialisation, the constructor is only neccesary when creating an instance of the base class directly for other (verbose) purposes.

If i remove the base constructor i get an error on the sub-class constructor saying the base constructor doesn't take 0 arguments. How can i avoid this?

Here's the base class:

public class ExportData
{
    private tData _Data;
    private ResStrings _diaStrings;

    public ExportLines(tData Data, ResStrings diaStrings)
    {
        _Data = Data;
        _diaStrings = diaStrings;
    }
}

Thanks in advance.

like image 512
Dan Hall Avatar asked Jan 05 '23 03:01

Dan Hall


2 Answers

A constructor of the base class is always used - but when the base class has no explicitly defined constructor, C# will generate a public parameterless constructor automatically.

Similarly, if you don't explicitly mention : base(...) in your derived class, C# assumes you want to use the parameterless constructor of the base class.

As soon as you define a constructor, the parameterless constructor is not automatically generated anymore, and so you have to call : base(...).

You can easily change this by adding such a constructor to the base class:

public class ExportData
{
    protected ExportData()
    {
    }
}

By making this constructor protected, only classes that inherit from ExportData can use this constructor, and they no longer have to include : base(...).

like image 187
C.Evenhuis Avatar answered Jan 13 '23 13:01

C.Evenhuis


You can always have a parameterless constructor in the base class that does all the initialising it needs to i.e.:

public ExportData()
{
    //Initialising here
}

And then in your example just call base() i.e.

public ExtendedExportData(tData Data, ResStrings diaStrings)
    : base()
like image 38
TheLethalCoder Avatar answered Jan 13 '23 13:01

TheLethalCoder