Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

I have a struct type called Node like below:

struct Node
{
    int data;
    Node next; 
}

I get compile time error when I compile above code but If I make it a class everything is fine.

class Node
    {
        int data;
        Node next; 
    }

What is the difference between two ( I know one is struct ( value type ) and one is class(ref type ) ) ?

like image 345
Embedd_0913 Avatar asked Feb 18 '23 13:02

Embedd_0913


2 Answers

Have you ever programmed in C-class language? You know, classes/structures and pointers and such?

If you had so, then remember: in C# "classes" are passed "as pointers", while "structs" are passed in they raw binary form, they are copied around just like anything non-pointerish non-referencish in 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 placed anywhere directly. Such field is actually a 4/8 byte pointer/reference. The size of 'class X' is easily determinable. In contrast, in C# you cannot have a 'struct X' that contains a field of type 'struct X'. Such field would be embeded in the outer struct directly, not by pointer/reference. What would be the size of the 'struct X' if it contained another 'struct X' which surely by its definition would contain another 'struct X' that would contain .... where would be the end? How would you mark the end? How the compiler/runtime would know how much space to allocate when you write "new X()" ? Just as in C/C++ you cannot create recursively nested types directly (you can do that only by pointers/references), here in C# you cannot create recursive structs.

like image 133
quetzalcoatl Avatar answered Mar 02 '23 21:03

quetzalcoatl


If you define class, Node is just reference to reference type Node. In strucure case you have nesting of Node stuct i.e. cyclic nesting Node in Node.

like image 32
Hamlet Hakobyan Avatar answered Mar 02 '23 20:03

Hamlet Hakobyan