Does not contain a constructor that takes 0 arguments

c#-4.0, inheritance

Solution

Several rules about C# come into play here:

Each class must have a constructor (In order to be, well constructed)

If you do not provide a constructor, a constructor will be provided for you, free of change, automatically by the compiler.

This means that the class

class Demo{}

upon compilation is provided with an empty constructor, becoming

class Demo{
   public Demo(){}
}

and I can do

Demo instance = new Demo();

If you do provide a constructor (any constructor with any signature), the empty constructor will not be generated

class Demo{
   public Demo(int parameter){}
}

Demo instance = new Demo(); //this code now fails
Demo instance = new Demo(3); //this code now succeeds

This can seem a bit counter-intuitive, because adding code seems to break existing unrelated code, but it's a design decision of the C# team, and we have to live with it.

When you call a constructor of a derived class, if you do not specify a base class constructor to be called, the compiler calls the empty base class constructor, so

class Derived:Base {
   public Derived(){}
}

becomes

class Derived:Base {
   public Derived() : base() {}
}

So, in order to construct your derived class, you must have a parameterless constructor on the base class. Seeing how you added a constructor to the Products, and the compiler did not generate the default constructor, you need to explicitly add it in your code, like:

public Products()
{
}

or explicitly call it from the derived constructor

public FoodProduct()
       : base(string.Empty, string.Empty, 0, 0, 0, 0)
{
}

Problem

I get an error stating "Products does not contain a constructor that takes 0 arguments" from the following code: ``` public class Products { string id; string name; double price; int soldCount; int stockCount; public Products(string id, string name, double price, int soldCount, int stockCount, double tax) { this.id = id; this.name = name; this.price = price; this.soldCount = soldCount; this.stockCount = stockCount; } } //I have got some get and set values for the code above //but it would have been too long to put in here public class FoodProducts : Products { public FoodProduct() { Console.WriteLine("This is food product"); } public void Limit() { Console.WriteLine("This is an Attribute of a Product"); } } ```

Original source