Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no cyclic layout issue for classes in C#?

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?

like image 659
nawfal Avatar asked Jan 13 '13 23:01

nawfal


1 Answers

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...

like image 88
Jon Skeet Avatar answered Oct 05 '22 07:10

Jon Skeet