Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is parent's constructor getting called?

I have an asbtract class Example. Another generic class UsesExample uses it as a constraint, with a new() constraint. Later, I create a child to Example class, ExampleChild, and use it with generic class. But somehow when the code in generic class tries to create new copy, it invokes not the constructor in the child class, but the constructor in the parent class. Why does it happen? Here's the code:

abstract class Example {

    public Example() {
        throw new NotImplementedException ("You must implement it in the subclass!");
    }

}

class ExampleChild : Example {

    public ExampleChild() {
        // here's 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();

    }

}
like image 497
Max Yankov Avatar asked Dec 02 '22 22:12

Max Yankov


2 Answers

When you crate an object, all constructors are called. At first the base class constructor constructs the object so that the base members are initialized. Later the others constructors in hierarchy are called.

This initialization may call static functions so that it makes sense to call the constructor of an abstract base class event if it has no data members.

like image 153
harper Avatar answered Dec 04 '22 12:12

harper


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

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

is really turned into:

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

by the compiler.

You can read more on Jon Skeet's detailed blog post on C# constructors.

like image 28
goric Avatar answered Dec 04 '22 11:12

goric