-3

I have the next code in c #:

class Person
{
     private Person variable; // what this line mean
     ....
}

What does it mean for type of variable to be 'Person' ? It is not yet completely defined... Why would one use such class?

Alexei Levenkov
  • 94,391
  • 12
  • 114
  • 159

1 Answers1

0

It is pretty common for class to have variables of its own type. Standard case - element of binary tree:

 class TreeNode
 {
       public int Data {get;set;}
       public TreeNode Left {get;set;}          
       public TreeNode Right {get;set;}
 }

This means that instance of the class refers to some other instances it relates to in some way. Commonly it is some sort of parent-child (like in sample above) or ownership relation (i.e. CarComponent has more CarComponent like engine has valves).

As for naming of such construct - there is no common name for that. Sometimes "recursive class" or "self-referencing class" are used, but there is no formal name to my knowledge.

Note: class is reference type adding reference to an instance of the same type as field is perfectly fine. Note that this will not work with struct (as data must be part of the same object).

Alexei Levenkov
  • 94,391
  • 12
  • 114
  • 159