Reputation: 11
public class Node
{
public int Value { get; set; }
public Node Next { get; set; }
}
I am a complete beginner in programming. I decided to learn C# as my first programming language. I came across this code.
How is 'Node' defined as the datatype for Next? It is confusing me a lot.
Upvotes: 1
Views: 232
Reputation: 1330
Like other answers, this class represents a node for a linked list. In this case the Node
can point to another instance of Node.
Node
{
int Value = 1;
Node Next =============> Node {
} int Value = 2;
Node Next ===========> Node {
} int Value = 3;
Node Next =======> null
}
You don't usually come across classes having references to themselves like Node
.
Upvotes: 1
Reputation: 6610
This is a good question to ask as you're learning about C#. The key is that there are two kinds of types in C#: "value" types and "reference" types. See this question and its answers for more details.
Because Node
is declared as a class
, that means it is a reference type.
If you make a variable with a reference type, then that variable doesn't hold the data directly; instead, it holds a reference that can point to the data. By default, references have the special value null
, which means they don't point to anything. When you assign a variable e.g. myNode.Next = someOtherNode
, you don't copy the entirety of someOtherNode
to the Next
property; you just copy a reference to someOtherNode
into the property.
So by the Node
class itself having a Node
property, a Node
object doesn't actually contain another Node
object. The first object contains a reference to the second object. This allows one node to point to another node, which can then point to another node, and so on. A collection of nodes organized this way is called a linked list; in this case, it's a linked list of int
(32-bit integer) values.
If Node
were a value type (declared as a struct
instead of a class
), then there would indeed be a problem. Value type variables contain the data directly, so you cannot have an instance of a value type which contains another instance of that same value type.
Upvotes: 1
Reputation: 5277
That looks like a class defining a node in a singly linked list that stores integer values. Remember a class is just a definition of the shape of an object. This may work like:
var node1 = new Node { Value=1} ; node1.Node = new Node { Value=2};
Upvotes: 0
Reputation: 10874
This is called a linked list, an example of a recursive data structure. This can easily be instantiated in C# because the recursion can be ended by letting the last node in the list have a null value for the Next property.
Upvotes: 0