Can a Custom C# object contain a property of the same type as itself?

后端 未结 8 1290
情深已故
情深已故 2021-02-08 04:03

If I have created the following Employee object (simplified)...

 public class Employee
    {
        public Employee()
        {       
                


        
8条回答
  •  一整个雨季
    2021-02-08 04:19

    The only scenario where this isn't possible is with a struct; a struct is contained directly (rather than being a fixed-size reference to the data), so the size of an Employee struct would have to be "the size of the other fields plus the size of an Employee", which is circular.

    In particular you can't have:

    struct Foo {
        Foo foo;
    }
    

    (or anything else that would result in a circular size) - the compiler responds with:

    Struct member 'Foo.foo' of type 'Foo' causes a cycle in the struct layout

    However, in all other cases it is fine; with the issue of initialisation, I'd say: just leave it unassigned initially, and let the caller assign a value via the property.

提交回复
热议问题