Declaring variable of the same type of class that contains it

3

Greetings I've been studying data structures and I've run into a very curious syntax and I've been trying to find answers and I have not found them.

public class CNodo
{

    //Aqui colocamos el dato o datos que guarda el nodo
    private int dato;

    //Esta variable de referencia es usada para apuntar al nodo siguiente
    private CNodo siguiente = null;

    //Propiedades que usaremos
    public int Dato { get => dato; set => dato = value; }
    internal CNodo Siguiente { get => siguiente; set => siguiente =  value; }

    //Para su facil impresion
    public override string ToString()
    {
        return string.Format("[{0}]", dato);
    }
}

I have created a class called CNodo and within it I declared a variable called siguiente of type CNodo . The code does not have any errors. But I have a confusion. I have seen these types of variables in several codes and I still do not understand their functionality.

Do I want an explanation about the usefulness of these variable declarations?

Thank you very much.

    
asked by Abel De Jesús 12.10.2018 в 15:57
source

2 answers

1

This type of construction is used to generate lists, in particular linked lists. With this structure you can go through the list pointing to the next element of it in your field named as following.

In this case, it is very useful for handling batteries, queues, lists and trees.

    
answered by 12.10.2018 в 16:58
1

I'll give you an example, if you ever saw a table in SQL that is related to itself, this at the level of clases something very similar, taking as practical example a class Persona and we will try to identify the kinship between their parents, for which we would create a class with properties of the same type of class:

public class Persona
{
    public int Id { get; set; }

    public string Nombre { get; set; }
    public string Apellido { get; set; }
    public bool Sexo { get; set; }
    public Persona Padre { get; set; }
    public Persona Madre { get; set; }

}

This has several utilities such as being able to define hierarchies, trees, stacks, sequences, etc. I hope you serve, greetings

    
answered by 12.10.2018 в 17:10