Nivel 1 — Conceptos básicos
Tipos de valor frente a tipos de referencia
Notas originales de SunDiaL · Ver fuente en inglés
Este es el aspecto que más confunde a quienes empiezan a aprender programación. Es el tipo del tipo de datos.
Tipos de valor
Los tipos de valor se almacenan en la pila. Al asignar una variable a partir de otra, se copia el valor almacenado. Los tipos de datos que son tipos de valor son: booleanos, números, caracteres, cadenas y todas las estructuras.
En realidad, las cadenas son un tipo de referencia inmutable, lo que hace que se comporten como un tipo de valor para resultar más intuitivas.
Ejemplo:
int x = 1; //the value of x is 1 and is stored on the stack
int y = x; //the value of y is the value of x. which is 1, and is also stored on the stack
y = 2; //the value of y becomes 2.
Console.WriteLine(x); //will output 1
Console.WriteLine(y); //will output 2
Tipos de referencia
Los tipos de referencia se almacenan en el montículo, y su dirección se guarda en la variable situada en la pila. Al asignar una variable a partir de otra, lo que se copia es la dirección. Los tipos de datos que son tipos de referencia son… prácticamente todo lo que no sea un tipo de valor… es decir, las clases. Usaremos colecciones para escribir un ejemplo. Observa que el fragmento utiliza el bucle for.
List<int> list1 = [1, 2]; //list1 holds a reference (stored on the stack) which points to the actual list on numbers (stored on the heap)
List<int> list2 = list1; //list2 copies the reference from list1. This means that it is pointing to the same list of numbers on the heap
list1[0] = 3;
list2[1] = 4;
//write list1. Will outout 34
for(int i=0; i<2; i++)
{
Console.Write(list1[i]);
}
//write list2. Will also 34 since it is referencing the same list.
for(int i=0; i<2; i++)
{
Console.Write(list2[i]);
}