Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't structs contain nullable circular references?

I understand why structs can't contain circular references which lead to logical memory problems, but why doesn't a nullable reference circumvent this limitation? For example:

struct Foo
{
    Foo? bar;
}

Obviously this could very easily lead to stack overflows and circular references, if one wasn't careful, but shouldn't bar be a pointer to another Foo instance, and default to null? Or (more likely) do I not understand how nullable value types are laid out in memory?

(My background knowledge consists mainly of information from this question and answers.)

like image 634
dlras2 Avatar asked Nov 29 '22 09:11

dlras2


1 Answers

No, not quite. A nullable value type is really an instance of Nullable<> with a value type as the generic parameter. The question mark is just a shorthand.

Nullable is a struct, and therefore is a value type. Since it retains a reference to the Foo struct, you still have a circular reference consisting of value types.

like image 114
Andrew Avatar answered Dec 14 '22 05:12

Andrew