Reference Types and value types

All primitive types are structures. They are lightweight and don’t take more than 8 bytes. Arrays, strings are classes.

Structures are value types, and classes are reference types.

Memory is automatically allocated for value types. When value is out of scope, it is automatically and immediately removed from the memory by run time or CLR.

For reference types, we have to allocate memory manually. Thats why we use “new” operator. We tell run time to allocate memory to objects created with reference types. When value is out of scope, it is not removed automatically. There is a process called garbage collection done by run time or CLR which does this garbage collection. CLR looks at the objects that are not used and removes them from memory. Main difference between classes and structures is memory management.

Value types means, when we copy a value type to variable, copy of that value is taken and stored in memory to target variable.

Ex:

Int a=10;
Int b =a;
b++;
console.writeline(b,a);

This will display value of b as 11, and a as 10. When we declared b as a, value of a is copied and stored in memory and named as b. Thats why they are called value types, their values are copied in memory.

With reference types, from the name itself, it clearly shows, it is just a reference. Since objects are stored in memory, reference types are references to memory places. When declared to use the same value, both reference types(arr1 and arr2 in below example) will have same memory address.

If you declare array as :

Var arr1 = int[3] {1,2,3};
Var arr2 = arr1;
arr2[0]=0;

Now, if you use console.writeline(arr1[0]);, its value will be 0. Because both arr1 and arr2 are pointing to the same memory address. When you changed arr2, it automatically changes for arr1. But when you are using value types, and declare, int b = a, in above example, it copies a value and assigns to b. So, if you use b++, only b value is changed a is still 10.

Similarly, console.writeline(arr1[0],arr2[0]), both will have value 0.

Last updated