Skip to content

TypeLoadException if a struct S has a field static Generic<S> where Generic is struct Generic<T> #118782

@UlyssesWu

Description

@UlyssesWu

Description

A struct S cannot have a field which type is a generic struct GS which generic instance type is struct S itself.
It looks like some kind of limitation, but I could not find such limitation on the doc.

The closest limitation I've found is CS0523. However, when CS0523 is triggered, the code fails to compile and there’s a syntax error message. In my case, the code compiles and there’s no syntax error. It just throw a TypeLoadException when running.

Test failed from .NET Framework 4.8 to .NET 8.
However, it works on mono.

Reproduction Steps

Compile and run this code.

namespace MyNamespace;
public struct NativeArray<T> //where T : struct
{
}

public struct MyStruct
{
    public static NativeArray<MyStruct> MyArray;
}

internal class Program
{
    static void Main(string[] args)
    {
        MyStruct m;
        Console.WriteLine(m.ToString());
        return;
    }
}

Expected behavior

MyNamespace.MyStruct

Actual behavior

System.TypeLoadException:“Could not load type 'MyNamespace.MyStruct' from assembly 'MyTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.”

Regression?

Test failed on .NET Framework 2.0, 4.8, .NET 8.
However, it works on mono.

Known Workarounds

Do not use a static field since the bug is partially fixed by #6924.

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions