dotnet / dotnet/csharpstandard
16.4.10 Static Constructors (when run)
- Dominant language
- C#
- Stars
- 815
- Forks
- 99
- Avg merge
- 1d 14h
- Merged PRs (30d)
- 16
Description
From https://github.com/dotnet/csharplang/issues/1948
Consider [the following code](https://sharplab.io/#v2:EYLgtghgzgLgpgJwDQxAgrgOwD4AEAMABLgIwDcAsAFDW4BMxJA7NQN7WGeMBsxALIQCyEAJaYAFAEpCAXgB8hACZwAZhHQAbGOIBCAewBeACz0blkgHQAxKZSoBfatVgYAxjEL7jp5Ww5dSXi8TMzgpWQVSAE5xACIAZRgIGBFXQlc9TBd0dz0EWMk7LmIAZn5CG2lWQkcHIA==):
```csharp
using System;
class Program
{
static void Main() => default(Bozholde).F();
}
struct Bozholde
{
static Bozholde() => Console.WriteLine("Static constructor");
public void F() { }
}
```
This code outputs `Static constructor` before calling `F`. Tested online on sharplab.io, as well as with the fresh Visual Studio 2017 on .NET Fx 4.7.1 and .NET Core 2.0.
However [the spec](https://github.com/dotnet/csharplang/blob/master/spec/structs.md#static-constructors) doesn't list calling an instance method as a valid reason for triggering the static constructor:
> The execution of a static constructor for a struct type is triggered by the first of the following events to occur within an application domain:
>
> * A static member of the struct type is referenced.
> * An explicitly declared constructor of the struct type is called.
I believe, the bug is in the specification and must be corrected. [If not, it's a bug in compiler and must be moved to the appropriate repository.]
Contributor guide
Assessment
This issue has not been assessed yet.