Value Type and Reference Type in C#

What are Value Types and Reference Types?

In C#, data types are divided into two main categories: Value types and Reference types. Understanding the difference between these two is fundamental to working with variables, memory, and performance in C#.

Value Types

Value types hold the actual data in memory. When a variable of value type is assigned to another, the data is copied, meaning changes made to one variable do not affect the other. All the primitive data types in C# are value types, and they are stored in the stack memory.

Example of Value Types:

int a = 10;
int b = a;  // b gets a copy of a

a = 20;
Console.WriteLine(b);  // Output: 10
        

In this example, changing the value of a does not affect b because b holds a copy of a's original value.

Reference Types

Reference types store the reference (or address) of the data in memory, not the actual data itself. When a reference type variable is assigned to another, both variables point to the same memory location. This means that changes to one variable affect the other. Reference types are stored in the heap memory.

Example of Reference Types:

class Person
{
    public string Name;
}

Person p1 = new Person();
p1.Name = "John";

Person p2 = p1;  // p2 refers to the same object as p1
p2.Name = "Mike";

Console.WriteLine(p1.Name);  // Output: Mike
        

In this example, changing the name through p2 also changes it for p1 because both variables reference the same memory location.

Minimum and Maximum Range of Value Types

The following table lists the minimum and maximum values of common value types in C#:

Data Type Size (in bytes) Minimum Value Maximum Value
byte 1 0 255
int 4 -2,147,483,648 2,147,483,647
float 4 ~1.5 × 10^-45 ~3.4 × 10^38
double 8 ~5.0 × 10^-324 ~1.7 × 10^308
char 2 U+0000 U+FFFF

Different Types of Data Types

The following table categorizes the different types of data types in C#:

Category Data Type Description
Integral Types int Signed 32-bit integer
long Signed 64-bit integer
short Signed 16-bit integer
byte Unsigned 8-bit integer
Floating Point Types float 32-bit single-precision floating point
double 64-bit double-precision floating point
Character Type char Single Unicode character
Boolean Type bool Boolean value (true or false)
String Type string Sequence of characters