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 )
) ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With