Search code examples
c#oopinheritanceconstructordefault-constructor

There is no argument given that corresponds to the required formal parameter 'firstName' of 'Person.Person(string, string)'


Ok so I have two simple classes, Person and Employee.

Person:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

Employee:

public class Employee : Person
{
    public string DepartmentName { get; set; }
}

Simple right? Employee inherits person, but there is problem. The employee class is giving me an error that says that constructor of the parent class must be called. Now an answer on a similar question says that I should call the base class's constructor and it will resolve the problem. Which it does.

My question is why should I be calling the base class's constructor when employee class it self doesn't have a constructor of it's own?

A book name MCSD Certification 70-483 says that:

One oddity to this system is that you can make an Employee class with no constructors even though that allows the program to create an instance of the Employee class without invoking a Person class constructor. That means the following definition for the Employee class is legal:

public class Employee : Person
{
 public string DepartmentName { get; set; }
}

My case is exactly as same the one written on this book. The book says that its legal to inherit and not call the base class's constructor if the child doesn't have its own. Why am I still receiving this error? Even when though I have the same implementation.

Is this 2018 book outdated/has an error? Am I doing something wrong? or a new update in C# doesn't allow a child class if it doesn't call the parent's constructor?


Solution

  • It looks like this is a typo. Because each constructor of derived type in inheritance should call base constructor implicitly or explicitly.

    A constructor like this:

    public Employee () {}
    

    is implicitly:

    public Employee () : base() {}
    

    However, Person does not have parameterless constructor, so it is a reason of an error:

    CS7036 There is no argument given that corresponds to the required formal parameter 'firstName' of 'Person.Person(string, string)'

    What it is possible to do is to create constructor with default values:

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    
        public Person(string firstName = null, string lastName = null)
        {
            FirstName = firstName;
            LastName = lastName;
        }
    }
    

    Then Employee class without constructor will be eligible:

    public class Employee : Person
    {
         public string DepartmentName { get; set; }
    }