Skip to content

The constructor run ordering is incorrect for static constructors for PowerShell class #12450

@daxian-dbw

Description

@daxian-dbw

Prerequisites

  • Existing Issue: Search the existing issues for this repository. If there is an issue that fits your needs do not file a new one. Subscribe, react, or comment on that issue instead.
  • Descriptive Title: Write the title for this issue as a short synopsis. If possible, provide context. For example, "Typo in Get-Foo cmdlet" instead of "Typo."
  • Verify Version: If there is a mismatch between documentation and the behavior on your system, ensure that the version you are using is the same as the documentation. Check this box if they match or the issue you are reporting is not version specific.

Links

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_classes_constructors?view=powershell-7.5#constructor-run-ordering

Summary

The doc says:

For derived classes that inherit from another class, the ordering is:

1. The static constructor for the base class.
2. The static constructor for the derived class.

Actually, static constructors are not called in order of "base -> derived". When using a derived class,

  • if the derived class's static constructor doesn't depend on the base class, then its static constructor will be called first.
  • if the derived class's static constructor depends on the base class, then the base's static constructor will be called before the line of code that depends on base executes.

See PowerShell/PowerShell#26179 for details. The reported behavior about the calling order of static constructor is the same as regular .NET types.

Details

No response

Suggested Fix

Maybe we can just point users to the .NET doc about calling order of static constructors?

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-aboutArea - About_ topicsissue-doc-bugIssue - error in documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions