There is a base class and heir. Both have the same constructor parameters.

I was told that if the parameters are the same, then the constructor in the heir can be ignored or something like that .

However, while rummaging through Google, I did not find an example of inheritance with the same parameters, and in all examples the parameters of the base class and the heir were different.

In short, how should this code be written correctly?

class CustomCommand { public CustomCommand(string t, string a) { trigger = new Regex(t); triggerStr = t; ansver = a; } public virtual void Fire(string n, string m, string c) { } public Regex trigger; public string triggerStr; public string ansver; }; class EasyCommand : CustomCommand { public EasyCommand(string t, string a) : base(t, a) { } public override void Fire(string n, string m, string c) { m = "123"; } }; 
  • All right, otherwise and do not write. - Andrei NOP

2 answers 2

Constructors are not passed to the derived class during inheritance. And if a default constructor with no parameters is not defined in the base class, but only constructors with parameters, then in the derived class we must invoke one of these constructors via the keyword base .

 public class Person { public string FirstName { get; set; } public string LastName {get; set; } public Person(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } public void Display() { Console.WriteLine($"{FirstName} {LastName}"); } } public class Employee : Person { public string Company { get; set; } public Employee(string firstName, string lastName, string comp) : base(firstName, lastName) { Company = comp; } } 

If we remove the constructor definition from the Employee class:

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

In this case, we get an error, because the Employee class does not correspond to the Person class, and it does not invoke the constructor of the base class. Even if we added some constructor that would set all the same properties, we would still get an error:

 public Employee(string firstName, string lastName, string comp) { FirstName = firstName; LastName = lastName; Company = comp; } 

That is, in the Employee class, via the base keyword, you must explicitly call the constructor of the Person class:
Alternatively, we could define a parameterless constructor in the base class:

 public Person() { FirstName = "Tom"; LastName = "Johns"; Console.WriteLine("Вызов конструктора без параметров"); } 

Here is the complete article on Inheritance.

    Yes, you will have to implement constructors in the derived class, and use the base keyword in them to call the constructor of the base class, because the constructors are not inherited. We must explicitly prescribe them in the class of the heir, thereby indicating how the base class should be initialized.