Why is there no looping layouts for classes in C #?

public struct Unit { Unit u; } 

Causes:

The Struct element 'Unit.u' of type 'Unit' invokes a loop in the layout structure.

But

 public class Unit { Unit u; } 

compiles. I understand the problem, I suppose. After referencing the Unit object, an endless loop will be created, since it will have to initialize another Unit element and so on. But why does the compiler limit the problem only to structs ? Isn't the problem persisting for the class too? Did I miss something?

+8
c # struct class cyclic-reference circular-dependency
source share
4 answers

The problem is the layout.

When Unit is a structure, any value for Unit must contain another value of the same type (and thus the same size), ad infinitum. It's impossible. I suppose you can argue that without any other fields, the fields for Unit should not contain memory, so you can contain it inside yourself, but I believe that the way the CLR works ensures that all structures occupy at least 1 byte .. .

When a Unit is a class, the Unit object must contain a reference to another Unit object. There are no storage issues, and the value can start from scratch.

Think of it this way: you cannot have a house in which there is another house built from the same plan, but you probably have a house in which there is a piece of paper with a similar address on it ...

+20
source share

Classes are reference types, so I assume that the difference is that in the class example, it should only keep a reference to another instance. For your struct , like a value, it will have to include the whole structure again, hence an infinite loop.

+3
source share

struct automatically initialized with a value, so in your example, the Unit value contains a Unit value that contains a Unit value that contains a Unit value, etc ...

In the class example, only a reference to null initialized, which does not have infinite regression. However, you ran into a similar problem if you did the following:

 class Unit { Unit mUnit = new Unit(); } 

Now build the construction of Unit a Unit , which builds a Unit , etc. In this case, you will encounter an overflow of the stack stack at runtime if you try to create an instance of the Unit object.

I thought you could avoid the struct problem by using a type with a null value, but the problem remains. I believe this is because the nullable struct value is still created when set to null .

+2
source share

Because Struct value type . Unit can hold value as itself? I think that this is impossible.

But when Unit is class , class reference type . A Unit object may contain a reference to another Unit object. This is normal.

+1
source share

All Articles