Light Mode Image

C# Value Type and Reference Type

In C#, variables are classified into two main categories based on the type of data they hold. Value types and Reference types. 

 

This classification determines how the data is stored in memory and how variables interact with that data.

 

1. Value Types

 

Value types directly contain their data, and instances of value types are stored in a location in memory called the stack.

 

Examples of value types include simple data types like integers (int), floating-point numbers (float), characters (char), and custom structs.

 

When you assign a value type to another variable or pass it as a method parameter, a copy of the data is created. Changes to one variable do not affect the other.

int a = 5;
int b = a; // 'b' gets a copy of the value of 'a'
b = 10;    // Changing 'b' does not affect 'a'

 

2. Reference Types

 

Reference types store a reference to the memory location where the actual data is held (usually on the heap). The variable itself contains a reference (memory address) to the location where the data is stored.

 

Examples of reference types include classes, interfaces, arrays, and strings.

 

When you assign a reference type to another variable or pass it as a method parameter, you're copying the reference, not the actual data. Both variables now refer to the same underlying data in memory.

int[] array1 = { 1, 2, 3 };
int[] array2 = array1; // Both 'array1' and 'array2' refer to the same array
array2[0] = 100;       // Changing 'array2' also changes 'array1'

 

Understanding the distinction between value types and reference types is crucial for writing efficient and correct code in C#. It has implications for memory management, performance, and behavior when working with variables and objects in your programs.