C# Value types and Reference types

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.

  1. Global Memory: Actually, it is a C language concept where global variables will make use of this global memory. These variables allocate memory at the starting of the application. They will remain until the lifetime of the application.
  2. Stack Memory: 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.
  3. Heap Memory: Memory requirements at runtime of the application fulfill from the heap memory. When some memory allocates to the heap variable, once its job completes, the memory must return to the Heap (deallocate) for the reuse of it by another variable. 
C# Value Types and Reference Types

C# Value Type

In general, all the basic Data Types, structures, Enum will come under value type. 

In a sense, the C# 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 if it is a member of an object, it is allocated 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 Heap.

In a real-time environment, all the memory-related tasks are managed 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.