Nivelul 1 — Noțiuni de bază
Tipuri valoare versus tipuri referință
Note originale de SunDiaL · Vezi sursa în engleză
Acesta este aspectul cel mai derutant pentru cei care încearcă să învețe programarea. Este tipul tipului de date.
Tipuri valoare
Tipurile valoare sunt stocate pe stivă. Când atribui unei variabile valoarea alteia, valoarea stocată este copiată. Tipurile de date care sunt tipuri valoare sunt: booleenele, numerele, caracterele, șirurile de caractere și toate structurile.
Șirurile de caractere sunt, de fapt, un tip referință imuabil, ceea ce le face să se comporte ca un tip valoare, pentru a fi mai intuitive.
Exemplu:
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
Tipuri referință
Tipurile referință sunt stocate pe heap, iar adresa lor se află în variabila de pe stivă. Când atribui unei variabile valoarea alteia, se copiază adresa. Tipurile de date care sunt tipuri referință sunt... cam tot ce nu este un tip valoare... adică clasele. Vom folosi colecții pentru un exemplu (observă că fragmentul folosește bucla 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]);
}