Question

I have a simple class with 2 constructors.

The first (default) constructor that takes no parameters constructs all the properties so they are not null once this object is instantiated.

the second constructor that takes an int parameter does a lot more logic, but it also need to do exactly what the default constructor does with regards to setting up the properties.

Is there away I can inherit from this default constructor so im not duplicating code?

code below...

public class AuctionVehicle
{
    public tbl_Auction DB_Auction { get; set; }
    public tbl_Vehicle DB_Vehicle { get; set; }
    public List<String> ImageURLs { get; set; }
    public List<tbl_Bid> Bids { get; set; }
    public int CurrentPrice { get; set; }

    #region Constructors

    public AuctionVehicle()
    {
        DB_Auction = new tbl_Auction();
        DB_Vehicle = new tbl_Vehicle();
        ImageURLs = new List<string>();
        ImageURLs = new List<string>();
    }

    public AuctionVehicle(int AuctionID)
    {
        // call the first constructors logic without duplication...

        // more logic below...
    }
}
Was it helpful?

Solution

You can do it like this:

public AuctionVehicle(int AuctionID) : this() 
{
   ...
}

OTHER TIPS

public AuctionVehicle(int AuctionID) : this()
    {
        // call the first constructors logic without duplication...
        // more logic below...
    }

Or factor it out to a private method which contains the common logic.

public AuctionVehicle(int AuctionID)
    : this()// call the first constructors logic without duplication...
{
    // more logic below...
}

inheritance from constructor is not allowed in c#

Reason :-

If constructor inheritance were allowed, then necessary initialization in a base class constructor might easily be omitted. This could cause serious problems which would be difficult to track down. For example, if a new version of a base class appears with a new constructor, your class would get a new constructor automatically. This could be catastrophic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top