Dan Hall Dan Hall - 1 month ago 5
C# Question

How to avoid calling the base class constructor

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.

Answer

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