Detailed explanation of C# constructor execution order
When defining a constructor in C#, a key question is: Is the constructor of the current class executed before or after calling the base class constructor?
Execution order
The execution sequence follows the following steps:
- Member variables of all classes in the inheritance hierarchy are initialized to default values.
- Start with the most derived class:
- Execute a variable initializer for the most derived type.
- The constructor chain determines the base class constructor to be called.
- Initialize the base class (apply these steps recursively).
- Constructor bodies in this class's inheritance chain are executed sequentially.
- Please note that unlike Java, the base class is initialized after the variable initializer is executed.
Example
Consider the following class hierarchy:
<code class="language-csharp">class Base
{
public Base(int param1)
{
// 构造函数主体
}
}
class Derived : Base
{
public Derived(int param1, int param2) : base(param1)
{
// 构造函数主体
}
}</code>
Copy after login
When creating a Derived instance, the execution sequence is as follows:
- Assign default values to the member variables of Base and Derived.
- Execute Derived’s variable initializer and set its own member variables.
- Call the base class constructor (Base(int param1)) with the specified parameters.
- Execute the constructor body of Derived.
The above is the detailed content of What's the Constructor Execution Order in C# Inheritance?. For more information, please follow other related articles on the PHP Chinese website!