ITADN

[Proposal]: Relaxed restriction on generic struct with explicit layout

#9898ClosedsamyycX 创建于 2025-12-20
S
samyycXcommented
# Relaxed restriction on generic struct with explicit layout ## Summary Currently, when we declare a generic struct with explicit layout, it causes a runtime exception: `System.TypeLoadException: because generic types cannot have explicit layout.` If I'm not mistaken, this behavior is to prevent uncertain sizes on generic members that break alignment and cause other issues. However, sometimes generics can be used for other purposes without causing such issues. The following simple case represents this scenario: ```csharp public interface IExampleInterface { public static abstract void InterfaceMethod(); } public interface IImplementInterface : IExampleInterface { static void IExampleInterface.InterfaceMethod() { Console.WriteLine("Implemented!"); } } [StructLayout(LayoutKind.Explicit)] public struct ExampleStruct<T> where T : IExampleInterface { [FieldOffset(0x0)] public uint abc; public void UseInterfaceMethod() { T.InterfaceMethod(); } public static void Test() { var a = new ExampleStruct<IImplementInterface>(); a.UseInterfaceMethod(); } } ``` As you can see, the generic type parameter is used solely for static methods and does not cause any memory layout issues. Therefore, the restriction should be relaxed to, for example, prevent structs with explicit layout from having generic-typed fields, rather than prohibiting all generic structs with explicit layout. I roughly checked related questions and didn't find a issue that related to this problem, i'm sorry if this is already discussed.
关闭于 2025-12-20 2 条评论