1

I narrowed down the program to:

using System;
using System.Runtime.InteropServices;

abstract class Abstract {
  public int a;
}

[StructLayout(LayoutKind.Sequential)]
sealed class TestClass : Abstract {
  public int x;
}

sealed class Container {
  public TestClass tc;
}

class Program
{
  static void Main(string[] args)
  {
    Console.WriteLine("START");
    foreach (var field in typeof(Container).GetFields()) {
      Console.WriteLine($"{field.Name}: {field.FieldType}");
    }
  }
}

Outputs:

START
Unhandled exception. System.TypeLoadException: Could not load type 'TestClass' from assembly 'DEL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the format is invalid.
   at System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
   at System.Reflection.RtFieldInfo.InitializeFieldType()
   at Program.Main(String[] args) in /code/Program.cs:line 27

Why does the exception happen? Can I use StructLayout on the subclass?

Carl Walsh
  • 6,100
  • 2
  • 46
  • 50

1 Answers1

0

Reflection with .FieldInfo is a red herring; TestClass is inherently broken, which can be seen by using the type directly: If Main() contains the line var tc = new TestClass(); then "START" will never be printed because the method never even starts.

The problem is the same as in https://stackoverflow.com/a/39741897/771768 and https://stackoverflow.com/a/30968801/771768 but Google won't find those if you include reflection in the search terms.

The base class needs the StructLayoutAttribute also:

[StructLayout(LayoutKind.Sequential)]
abstract class Abstract {
  public int a;
}
Carl Walsh
  • 6,100
  • 2
  • 46
  • 50