16

Create a console app to reproduce:

struct Test
{
    public static readonly Test? Null = null;
}

class Program
{
    static void Main(string[] args)
    {
        var t = Test.Null;
    }
}

It is compilable, but we will have the following at run time:

An unhandled exception of type 'System.TypeLoadException' occurred in mscorlib.dll. Additional information: Could not load type 'ConsoleApplication17.Test' from assembly 'ConsoleApplication17, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

This approach solves the problem:

struct Test
{
    public static Test? Null => null;
}
AGB
  • 2,230
  • 1
  • 14
  • 21
Dmitry Nogin
  • 3,670
  • 1
  • 19
  • 35

1 Answers1

17

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.

Source : Static fields should not contribute to cyclic struct layout #4049

Xiaoy312
  • 14,292
  • 1
  • 32
  • 44