Why can't I have the same property of type struct in struct in C #?

I have a type struct

called Node as shown below:

struct Node
{
    int data;
    Node next; 
}

      

I am getting a compile time error when I compile the code above, but if I do this class everything is fine.

class Node
    {
        int data;
        Node next; 
    }

      

What is the difference between the two (I know one - struct ( value type )

and one - class(ref type )

)?

+3


source to share


2 answers


Have you ever programmed in a C class language? You know classes / structures and pointers, etc.

If you had it, then remember: in C # "classes" are passed "as pointers", and "structs" are passed in raw binary form, they are copied around just like anything that does not contain pointers, does not reference C / C ++. All other restrictions for nesting are preserved, just named differently.



In C #, you can have a "class X" containing a field of type "class X" because "classes" are never directly placed anywhere. Such a field is actually a 4/8 byte pointer / reference. The size of the "class X" is easy to determine. In contrast, in C #, you cannot have a "structure X" that contains a field of type "struct X". Such a field will be embedded in the external structure directly, and not by pointer / link. What would be the size of the "structure X" if it contained another "structure X" which would surely by definition have another "structure X" that would contain .... where would the end be? How would you mark the end? How will the compiler / runtime know how much space is allocated when writing "new X ()"? As in C / C ++,you cannot create recursively nested types directly (you can only do this with pointers / references), here in C # you cannot create recursive structures.

+2


source


If you define class

, Node

- it is simply a reference to the type of link Node

. In the structural case, you have an attachment Node

i.e. Looping Node in Node.



+3


source







All Articles