Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static member causes Cycle in the struct layout

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

like image 745
Estecka Avatar asked Nov 22 '17 20:11

Estecka


1 Answers

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.

like image 66
Estecka Avatar answered Nov 16 '22 19:11

Estecka