Skip to content

Allow explicit control of beforefieldinit (especially with NRTs) #3080

Description

@mikernet

As a library developer I'm constantly mangling code that would otherwise be much simpler and easier to understand to avoid writing a static constructor that causes the beforefieldinit flag to be removed. Usually, this involves adding a superfluous static bool _initialized = Initialize() field or returning one of the field values with the Initialize() method and setting the rest of the fields inside it. This means my read-only fields can't be marked readonly, and has now become more of a burden with NRTs because now I have to make reference fields all nullable or silence the warning by setting them to default!.

Can we please add a [BeforeFieldInit(bool)] attribute that controls static initialization behavior?

This is a long-standing issue that I've seen discussed countless times in other places (StackOverflow questions, forum posts, team meetings, library PRs, also just found this one in Roslyn: dotnet/roslyn#4448) with a very simple fix which will make NRTs much more pleasant. I think that makes it a good candidate for immediate implementation. It will also remove the need to have empty static constructors which often get mistaken for something that can be removed with no undesirable effects.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions