Skip to content

Static fields should not contribute to cyclic struct layout  #5479

Closed

Description

@jaredpar

Consider the following code:

class Program
{
    static void Main(string[] args)
    {
        var x = MyStruct.Empty;
    }

    public struct MyStruct
    {
        public static readonly MyStruct? Empty = null;
    }
}

This code will compile with C# 6.0 and is legal according to the CLI spec. The type definition is recursive but the layout of the struct is not because the field involved here is static. The CLR is unable to handle this though and fails at runtime with a TypeLoadException:

Unhandled Exception: System.TypeLoadException: Could not load type 'ConsoleApplication1.Program+MyStruct' from assembly 'ConsoleApplication59, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

Activity

  1. jkotas commented on Apr 1, 2016

    @jkotas
    Member

    This is known implementation limitation in CoreCLR - both the instance and static field layout is done together that results into this error. It is not easy to fix.

  2. BBI-YggyKing commented on Oct 20, 2016

    @BBI-YggyKing

    Static is one case, but another is the case of unreferenced generic type parameters. As pointed out elsewhere by Eric Lippert, the following code compiles, but throws a TypeLoadException when run:

    struct N<T> {}
    struct M { public N<M> E; }

    Is this a result of the same "known implementation limitation"?

  3. transferred this issue fromdotnet/coreclron Jan 30, 2020
  4. added this to the Future milestone on Jan 30, 2020
  5. mangod9 commented on Sep 16, 2020

    @mangod9
    Member

    Closing since there doesnt seem to be any particular reasons to be fix in the near term.

  6. ghost locked as resolved and limited conversation to collaborators on Jan 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions