Why is the call to the parent constructor called?

I have an asbtract class. Another common UsesExample class uses it as a constraint, with a new () constraint. Later I create a child in the Example, ExampleChild class and use it with a generic class. But for some reason, when the code in the generic class tries to create a new copy, it does not call the constructor in the child class, but the constructor in the parent class. Why is this happening? Here is the code:

abstract class Example { public Example() { throw new NotImplementedException ("You must implement it in the subclass!"); } } class ExampleChild : Example { public ExampleChild() { // here the code that I want to be invoken } } class UsesExample<T> where T : Example, new() { public doStuff() { new T(); } } class MainClass { public static void Main(string[] args) { UsesExample<ExampleChild> worker = new UsesExample<ExampleChild>(); worker.doStuff(); } } 
+4
source share
3 answers

When you create an object, all constructors are called. First, the base class constructor constructs the object so that the base elements are initialized. Other constructors in the hierarchy will be called later.

This initialization can call static functions, so it makes sense to call the constructor of the abstract event of the base class if it has no data.

+8
source

Whenever you create a new instance of a derived class, the constructor of the base class is called implicit. In your code

 public ExampleChild() { // here the code that I want to be invoked } 

really turns into:

 public ExampleChild() : base() { // here the code that I want to be invoked } 

the compiler.

You can learn more about Jon Skeet more about the blog on C # constructors.

+8
source

In a derived class, if the constructor of the base class is not explicitly called using the base keyword, then the default constructor, if any, is called implicit.

from msdn Alternatively, you can read here

+2
source

Source: https://habr.com/ru/post/1415745/


All Articles