Search code examples
c#definition

declare variable of a type X in class X when defining my class X


I know that the title is not clear but sorry for my english I did not find how to formulate my question. So I hope below I could explain it further.

In fact I was reading a code where the user, when he was defining a class (let's called X), he declared a table of X (in the class definition).

Coming from C++, this is not possible as the type X is incomplete at that stage.

and another question : in the ctor the user allocate 10 elements so was thinking that it may be an infinite loop as for each instance of X we allow 10 elements which was not the case !

So does C# allow such behavior ?

//here we start the class definition
class X
{
    X[] Items = null;  // and here we declare a table of X elements ???

    public X()
    {
        Items = new X[10];  // and here we allocate 10 elements of X  ???
    }
}

Solution

  • In C#, there is no problem with incomplete types.

    On the other hand, I see what you mean by infinite loop. But this is also not the case, because only the array is allocated (in C++ an array of pointers), so these pointers are all NULL, the default constructor is not called.