public struct Unit
{
Unit u;
}
Causes:
Struct member 'Unit.u' of type 'Unit' causes a cycle in the struct layout.
But
public class Unit
{
Unit u;
}
compiles. I understand the problem I suppose. An endless cycle will be formed when referencing a Unit
object since it will have to initialize another member Unit
and so on. But why does the compiler restrict the problem just for structs
? Doesn't the issue persist for class
too? Am I missing something?
The problem is in terms of layout.
When Unit
is a struct, any value for a Unit
would have to contain another value of the same type (and thus the same size), ad infinitum. That's impossible. I suppose you could argue that with no other fields, the fields for Unit
should take up no memory, so you could contain it within itself - but I believe the way the CLR works ensures that all structs take up at least 1 byte...
When Unit
is a class, a Unit
object only has to contain a reference to another Unit
object. No storage problems, and the value can be null to start with.
Think of it this way: you can't have a house which contains another house constructed from the same blueprint, but you can certainly have a house which contains a piece of paper with a similar house's address on it...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With