There are two kinds of types in C#: reference and value.
Reference Type
The reference type variable doesn’t store the value directly; it stores the memory address of the variable. It points to the memory location, which has the value. Examples of the reference types:
- string
- class
- record
Since the reference type stores a pointer to the memory location, we can see this bizarre behavior of the code:
Employee employee1 = new Employee
{
ID = 1,
FullName = "Harry Potter"
};
Employee employee2 = employee1;
employee2.FullName = "Ron Weasley";
// Output: Ron Weasley
Console.WriteLine(employee1.FullName);
public sealed class Employee
{
public int ID { get; set; }
public string? FullName { get; set; }
}
The variable employee2 points to employee1. When we changed employee2’s full name, we changed the value inside the memory address pointed from variable employee1. That’s why the employee’s full name is now Ron Weasley instead of Harry Potter.
Value Type
Value type, on the other hand, stores the value itself rather than its memory allocation. Examples of value types:
- int
- bool
- struct
To demonstrate the difference between reference and value types, we change the data type of the above example to struct:
Employee employee1 = new Employee
{
ID = 1,
FullName = "Harry Potter"
};
Employee employee2 = employee1;
employee2.FullName = "Ron Weasley";
// Output: Harry Potter
Console.WriteLine(employee1.FullName);
public struct Employee
{
public int ID { get; set; }
public string? FullName { get; set; }
}
The compiler creates another copy of the variable, and each copy has its value. Generally, value types will have an initial value (cannot be null) because it holds a value, not a pointer to a specific memory address. Since it is impossible to list out all datatypes for either reference or value types, we have a method to differentiate both:
Console.WriteLine(typeof(int).IsValueType); // True
Console.WriteLine(typeof(string).IsValueType); // False
Console.WriteLine(typeof(Employee).IsValueType); // False
public sealed class Employee { }
Read more:
Leave a Reply