C# Value Types directly hold the value — for example, All Basic Types, Structures, and Enum. However, C# Reference Types contain the reference to the value on the Heap — for example, String, Object, Class, Array, Delegates.
C# Value types and Reference types
Types of memory allocated to a variable:
Before moving on to the category of data types (C# Value types and Reference types), let us have a quick look at memory classification in an application.
- Global: Actually, it is a C language concept where global variables will make use of this global memory. These variables allocate memory at the start of the application. They will remain until the lifetime of the application.
- Stack: Used by the local variables of a method. When a method invokes, a stack of memory allocates to that particular local variable. The stack will clear when the method returns.
- Heap: Memory requirements at runtime of the application will be fulfilled from the heap memory. When some memory allocates to the heap variable, once its job completes, it must return to the Heap (deallocate) for the reuse of it by another variable.
C# Value Type
In general, all the basic Data Types, structures, and Enum will come under the C# value type.
In a sense, the value type is the memory allocated to the variable containing the variable’s actual value.
Based on the scope of the variable, memory allocates to the Value types. If it is a local variable or parameter, it allocates stack memory. In case it is a member of an object, it will allocate memory on Heap.
C# Reference type
The memory allocated to the C# reference types will never hold the actual value of a variable. Instead, it holds the reference to the Value on the Heap.
In a real-time environment, all the memory-related tasks will manage by the Dot Net through memory management.
But as a programmer, it is better to know this so that you can optimize your code more efficiently and come up with better performance.