Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do i get a "cycle in the struct layout" with phantom types in c#? [duplicate]

Tags:

c#

struct

mono

example:

struct Id<T> {
  int id;
}

struct Thing {
  public Id<Thing> id;
}

this causes a cyclic struct layout, but i don't see the cycle. if Id had a field of type T, sizeof would be undefined, but it doesn't.

is this a mono bug, or part of the spec?

like image 714
notallama Avatar asked Apr 07 '15 15:04

notallama


1 Answers

As discussed in comments, while this code compiles using the MS C# compiler, it doesn't actually execute - it gives a TypeLoadException in runtime. Note that the problem only appears when both the types are struct. So the question is, is this a problem of the C# compiler or the runtime?

Since the runtime is also covered by its own specification, I went through all the pieces of the CLI specification that were even vaguelly relevant, and I didn't find anything that would prohibit this. Not in IL definition (obviously, since the IL is considered valid), and not in the runtime metadata structures.

Given this, I'm more in favour of calling the runtime implementation flawed. I suspect that when the Mono team was faced with this issue, they considered adding a compiler error for this situation being the lesser evil. Or maybe they just evaluate the cyclic struct constraint incorrectly :)

It might even be possible that it didn't use to crash in runtime, making the C# compiler even more right. I have no way of verifying this, of course :)

Sadly, this means that you can't use that handy construct of yours. Either make sure one of the types is a class, or you'll just have to make a different type for each of those IdOfSomething of yours. Just be glad the Mono C# compiler told you so before you found out in runtime :P

like image 145
Luaan Avatar answered Nov 04 '22 11:11

Luaan