Question

I'm designing a system that post-processes .NET assemblies and adds a new string field for every ldstr IL instructions it finds in the assembly. I'll be creating a new class and add the fields to it, then replace the ldstr instruction by a ldfld (or something) to access that field at runtime.

Is there any limit for the number of fields that a class can contain? I'm thinking of probably tens of thousands of fields right now.

I'm using Mono.Cecil for the IL work.

Was it helpful?

Solution

  • Ids in the Field metadata table are 3 bytes (the first byte out of four is used to identify the table). This means the maximum possible number of fields in an module (there is usually only one module in an assembly) is 16M.
  • The CLR seems to be limited to 64k - 1 fields in a single type. You won't be able to create a type with more fields than that using Reflection.Emit, or load such type with Reflection. But you can work around that by creating multiple types, each below this limit.
  • Mono Cecil doesn't have this limitation, so you can create a type that has more fields, but you won't be able to use it (at least not on MS implementation of .Net, Mono may behave differently).

This is based on looking at the ECMA CIL spec and my own tests.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top