Home >Backend Development >C++ >What's the Constructor Execution Order in C# Inheritance?

What's the Constructor Execution Order in C# Inheritance?

DDD
DDDOriginal
2025-01-22 23:47:14308browse

What's the Constructor Execution Order in C# Inheritance?

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:

  1. Member variables of all classes in the inheritance hierarchy are initialized to default values.
  2. 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.
  3. 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>

When creating a Derived instance, the execution sequence is as follows:

  1. Assign default values ​​to the member variables of Base and Derived.
  2. Execute Derived’s variable initializer and set its own member variables.
  3. Call the base class constructor (Base(int param1)) with the specified parameters.
  4. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn