Compiler Error CS0523
Struct member 'struct2 field' of type 'struct1' causes a cycle in the struct layout
The definitions of one or more structs include recursive references that form a cycle. This limitation only applies to structs, since structs are value types. To create recursive references, declare your types as classes, which are reference types.
Example 1
The following sample shows how a self referential type can cause CS0523:
// CS0523.cs
// compile with: /target:library
struct SelfReferentialStruct
{
public SelfReferentialStruct other; // CS0523
}
class SelfReferentialClass
{
public SelfReferentialClass other; // OK
}
When a self referential struct type is made, it contains a copy of the same type as a member. However, that member then has another copy, which continues recursively. As a result of the cycle, the size of the type cannot be determined and CS0523 is emitted.
Example 2
The following sample shows how a type reference cycle can cause CS0523:
// CS0523b.cs
// compile with: /target:library
struct ReferenceCycleStruct1
{
public ReferenceCycleStruct2 other; // CS0523
}
struct ReferenceCycleStruct2
{
public ReferenceCycleStruct3 other; // CS0523
}
struct ReferenceCycleStruct3
{
public ReferenceCycleStruct1 other; // CS0523
}
To resolve the errors above, you can adjust the references such that a cycle is no longer formed, or convert at least one of the struct types to a class. Similar to the previous example, ReferenceCycleStruct1
contains a ReferenceCycleStruct2
, and that contains a ReferenceCycleStruct3
, which eventually contains ReferenceCycleStruct1
again.
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for