Well, it is possible to define a generic structure in C# and it is also possible to use this generic structure as a field to another structure. I know that. But if the generic field uses the name of the parent structure as the generic type, things gets messy and I don't know why.
First of all, I rewrote my code by changing the design of the project and actually I found out that I don't really need the parent type in the second structure. However, the "WHY" question is still in my mind and I wanted to see if anyone here can offer an explanation.
Following is the code to reproduce this problem:
internal struct Boo<T>
{
public int IntValue;
}
internal struct Foo
{
public Boo<Foo> IntContainer;
public short ShortValue;
}
var fooVariable = new Foo();
Running this will result in the following error message, before even hitting the line creating a new instance of the Foo
(or any other line of the program for that matter). So it seems that the CLR having a problem defining the Foo
type even though the compiler is fine with it.
An unhandled exception of type 'System.TypeLoadException' occurred > in mscorlib.dll Additional information: Could not load type 'Foo' from assembly 'XXXXXX, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
I have earlier experience with this error happening with structures that CLR can't determine their sizes. However, this is not the case here as the size of Boo
and Foo
are both known and easily calculatable. In fact, the generic type has no effect on the size and the definition of the structure and so, this is not the case. Unless CLR doesn't check for this.
My other idea is that the CLR can't find a way to define the types as the design seems like a loop. But then, if I change any or both of structure definitions to class, the code works alright. So this must be something special to structures.