public class A { public A() { Console.WriteLine("мир!"); } } public class B : A { public B() { Console.WriteLine("Привет "); } } 

It is necessary to make the method constructor class A after the constructor class B

As a result, it should be displayed on the console:

Hello World!

  • You have no inheritance in the code. And if so, then the base class constructor is always called before the derivative constructor. - αλεχολυτ
  • @alexolut thanks for the comment, corrected. That is, so how do I want to fail? It’s just that I have a whole hierarchy here, and it’s necessary that the most basic class perform one task in the constructor, but only after other tasks are completed. Now it will be necessary to add everywhere on 1 line and not to be mistaken. - vmp1r3
  • Perhaps you just need to change the code of the designers themselves to achieve the desired effect. - αλεχολυτ
  • @alexolut is probably the only solution, although not the most optimal in my case. - vmp1r3
  • one
    Make a virtual method that will be called in the base constructor and override it in successors by explicitly calling the same parent method when you need it. - vitidev

1 answer 1

The base class constructor is executed before the constructor of the derived class. Instance constructors are executed in order A -> B.

Example:

 public class A { public A() { Console.Write("Hello "); } } public class B: A { public B() : base() { Console.Write("world!"); } } class Program { static void Main(string[] args) { var b = new B(); } } 

Hello world!

  • This is understandable, but how to do the opposite? - vmp1r3
  • one
    @PlasticBlock, No, this is not possible. - Lightness