public struct MyStruct {
static MyStruct? myProperty;
}
Trying to compile this will give me the error :Struct member 'myStruct.myProperty' causes a cycle in the struct layout
.
From what I gathered, this error usually happens when an instance of a struct contains its own struct as a property (which makes sense to me).
But here, it's about a static property, so I don't see how such a recursion could happen. Plus, the error only happens when declaring a Nullable struct, declaring a static non-nullable is safe.
What exactly is happeneing here that would cause a cycle ?
EDIT:
I did find the question I am supposedly a duplicate of; it explains why recursion happens when an Instance has a member of its own type, but this here is about static members.
I know from experience that struct can have static member of their own type that won't break at runtime, this specific code only seems to break because the static member is Nullable.
Secondly, multiple people told me right away that the code compile for them; déjà-vu, the "version" of c# I am working with is for Unity, so I assume this is yet another bug with their compiler, I'll adress this question to them.
@Evk pointed out this is actually a common issue:
https://github.com/dotnet/roslyn/issues/10126
While looking for a workaround I found two things:
One, properties with accessors work fine, so where a Readonly is needed you can just do this :
public struct myStruct {
public static myStruct? myProperty { get{ /*...*/ } }
}
Second, you can still store a field somewhere within the struct as long as it's nested :
public struct myStruct {
public static class nest {
public static Nullable<myStruct> myNestedProperty;
}
}
The latter is kinda ugly, (and fortunately I didn't need a setter), but at least that's a working workaround.
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