dotnet / dotnet/csharpstandard

Static constructor not triggered by inherited static method

Open
#1,315 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
C#
Stars
815
Forks
99
Avg merge
1d 14h
Merged PRs (30d)
16

Description

**Describe the bug**

In C# 7, section 15.12 (Static constructors) specifies that the static constructor is executed if:

> Any of the static members of the class are referenced.

According to section 15.3.1, static members inherited from a base class are also members of the derived class. However, the standard should not require executing the static constructor of the derived class when such a member is referenced.

**Example**

```csharp
class Program {
static void Main() {
// Reference a static member of the class System.Object.
// It is inherited by class B and thus also a member of class B.
// However I wouldn't expect the static constructor of B
// to be executed here.
object.ReferenceEquals(null, null);
}
}

class B {
static B() {
System.Console.WriteLine("How did we get here?");
}
}
```

**Expected behavior**

In 15.12 (Static constructors), specify that referencing a static member triggers the execution of static constructors only in the class where the member is declared, not in the classes that inherit the member.

**Additional context**

Found in .

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.