[C# Solution] Base Class Does Not Contain a Constructor That Takes 0 Arguments
Recently, I encountered an error while creating a constructor in a derived class. The error and code is given below.
Error:
Error 1 ‘Hello_World.Customer’ does not contain a constructor that takes 0 arguments
using System; namespace Hello_World { class Customer { public string _name; public Customer(string name) { _name = name; } public void PrintName() { Console.WriteLine(_name); } } class Customer2 : Customer { //Error public Customer2(string name) { _name = name; } } class Program { static void Main(string[] args) { Customer2 cust = new Customer2("Robert Marks"); cust.PrintName(); } } }
I tried my best to analyze the issue, but somehow I was not able to figure out that why derived class is not allowing me to create a constructor and showing this annoying error. After doing a little search over internet, I finally found the solution.
The problem was that I did not know the fact that whenever you try to call a constructor in derived class, then by default a base class parameterless constructor is called first. Also, if you are creating a custom constructor in base class, then your default base class parameterless constructor will be overridden. Now, in this case, there are 2 solutions. First solution, you need to explicitly create a base class parameterless constructor. Second solution, while creating your derived class constructor, you need to call a base class custom constructor using base keyword and passing required parameters to it. Examples for both solutions are given below.
First Solution : Parameterless Constructor
using System; namespace Hello_World { class Customer { public string _name; //Solution 1: Custom Constructor with 0 Arguements public Customer() { } public Customer(string name) { _name = name; } public void PrintName() { Console.WriteLine(_name); } } class Customer2 : Customer { //Error public Customer2(string name) { _name = name; } } class Program { static void Main(string[] args) { Customer2 cust = new Customer2("Robert Marks"); cust.PrintName(); } } }
Second Solution : Calling Base Class Constructor
using System; namespace Hello_World { class Customer { public string _name; public Customer(string name) { _name = name; } public void PrintName() { Console.WriteLine(_name); } } class Customer2 : Customer { //Solution 2: Calling Base Class Constructor using Base keyword and passing required // parameter public Customer2(string name) : base(name) { } } class Program { static void Main(string[] args) { Customer2 cust = new Customer2("Robert Marks"); cust.PrintName(); } } }