3

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.

Soroush Falahati
  • 2,196
  • 1
  • 27
  • 38
  • "So this must be something special to structures." - Of course. When Boo was using its T then this would lead to strange loop for computing the sizes. With classes Foo's size wouldn't depend on itself. – H H Feb 18 '17 at 18:21
  • 1
    You may have found a compiler or CLR bug but the real WHY is that you should never need or want this. – H H Feb 18 '17 at 18:22
  • @HankHolterman, True, So you are suggesting that it is both of these Ideas. The loop happens because the CLR tries to define the other type while also defining itself? However, 1. CLR should understand that the second type, has no dependency on the first one actually. So the size of it is not affected with the `Foo`. 2. The compiler should throw an error instead of leaving it to CLR. So if there is no explanation for this, it is probably a bug. Thanks for the comment. – Soroush Falahati Feb 18 '17 at 18:31

0 Answers0